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

时间:2016-12-09 16:28:03

标签: php variables multidimensional-array

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

$key='example';
echo $array[$key];

多维怎么样?

$keys='example[secondDimension][thirdDimension]';
echo $array[$keys];

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

4 个答案:

答案 0 :(得分:1)

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

请注意,您必须使用“[”和“]”包装所有键。

$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);

详细了解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;
}

为这个功能提供更好的名称将不胜感激^^

答案 1 :(得分:0)

您必须为数组的每个维使用单独的变量。您在多维数组中看到的常见模式,您需要对第二维执行某些操作,如下所示:

$pets = [
    'dog' => ['Jack', 'Fido', 'Woofie'],
    'cat' => ['Muggles', 'Snowball', 'Kitty'],
];

// Loop through keys in first dimension
foreach ($pets as $type => $names) {

    foreach ($names as $index => $name) {

        // And do something with second dimension using the variable
        // you've gained access to in the foreach
        $pets[$type][$index] = strtoupper($name);

    }

}

答案 2 :(得分:0)

这是不使用eval的解决方案:

$array = [
    'example' => [
        'secondDimension' => [
            'thirdDimension' => 'Hello from 3rd dimension',
        ],
    ],
];

$keys = '[example][secondDimension][thirdDimension]';

function get_array_value( $array, $keys ) {
    $keys = explode( '][', trim( $keys, '[]' ) );

    return get_recursive_array_value( $array, $keys );
}

function get_recursive_array_value( $array, $keys ) {
    if ( ! isset( $array[ $keys[0] ] ) ) {
        return null;
    };
    $res = $array[ $keys[0] ];
    if ( count( $keys ) > 1 ) {
        array_shift( $keys );

        return get_recursive_array_value( $res, $keys );
    } else {
        return $res;
    }
}

echo get_array_value( $array, $keys );

答案 3 :(得分:0)

要您使用 $b 数组跟随 $a 数组的嵌套键并获取 $c 中的值吗?

yarn run start

还是要为任意格式的字符串生成 $b 数组并获取 $c 作为参考?

<?php
$a = [ 'key_1' => [ 'key_2' => [ 'key_3' => 'value', ], ], ] ;
$b = ['key_1', 'key_2', 'key_3', ] ;
if ($b)
{
    $c = $a ; // $a is not copied (copy-on-write)
    foreach($b as $k)
        if (isset($c[$k]))
            $c = $c[$k] ;
        else
        {
            unset($c);
            break;
        }
    var_dump($c);
}
/*
output :
    string(5) "value"
*/