PHP:在多维数组中使用变量作为多个键

But*_*108 5 php variables multidimensional-array

在普通数组中,您可以选择这种方式

$key='example';
echo $array[$key];
Run Code Online (Sandbox Code Playgroud)

在多维中怎么样?

$keys='example[secondDimension][thirdDimension]';
echo $array[$keys];
Run Code Online (Sandbox Code Playgroud)

解决这个问题的正确方法是什么?

小智 2

我认为这个解决方案很好。

请注意,您必须用“[”和“]”将所有键括起来。

$array = array(
    'example' => array(
        'secondDimension' => array(
            'thirdDimension' => 'Hello from 3rd dimension',
        )
    ),
);

function array_get_value_from_plain_keys($array, $keys)
{
    $result;

    $keys = str_replace(array('[', ']'), array("['", "']"), $keys); // wrapping with "'" (single qoutes)

    eval('$result = $array' . $keys . ';');

    return $result;
}

$keys = '[example][secondDimension][thirdDimension]'; // wrap 1st key with "[" and "]"
echo array_get_value_from_plain_keys($array, $keys);
Run Code Online (Sandbox Code Playgroud)

了解有关eval()函数的更多信息

如果您还想检查该值是否已定义,则可以使用此函数

function array_check_is_value_set_from_plain_keys($array, $keys)
{
    $result;

    $keys = str_replace(array('[', ']'), array("['", "']"), $keys); // wrapping with "'" (single qoutes)

    eval('$result = isset($array' . $keys . ');');

    return $result;
}
Run Code Online (Sandbox Code Playgroud)

为该函数提供更好的名称将不胜感激^^

  • 使用“eval()”通常是一个坏主意,特别是在可能存在用户输入的情况下。 (2认同)