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

t5fffqht  于 2023-04-19  发布在  PHP
关注(0)|答案(6)|浏览(102)

此问题已在此处有答案

Access deep array value in php using an array of keys/indices in php? [duplicate](3个答案)
5天前关闭。
在一个普通的数组中你可以这样选择

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

在多维空间中如何?

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

怎么做才合适呢?

t9eec4r0

t9eec4r01#

我觉得这个办法不错。
请注意,您必须使用“[”和“]” Package 所有键。

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

给这个函数一个更好的名字将不胜感激^^

cig3rfwq

cig3rfwq2#

下面是一个不使用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 );
332nm8kg

332nm8kg3#

希望您使用**$B数组跟随$a数组的嵌套键并获取$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"
*/

或者你想为一个任意格式的字符串生成**$B数组,并获取$c**作为引用?

<?php
$a = [ 'key_1' => [ 'key_2' => [ 'key_3' => 'value', ], ], ] ;
$b = '[key_1][key_2][key_3]';
if ($b !== '')
{
    $b = explode('][', trim($b, '[]'));
    $c = &$a ;
    foreach($b as $k)
        if (isset($c[$k]))
            $c = &$c[$k] ;
        else
        {
            unset($c);
            break;
        }
}
var_dump($c);
$c = 'new val' ;
unset($c);
var_dump($a['key_1']['key_2']['key_3']);
/*
output :
    string(5) "value"
    string(7) "new val"
*/
lp0sw83n

lp0sw83n4#

使用eval()从Shopify客户数据数组中提取电话号码的简化示例:

// this is weird but whatever
    $arrayPaths = array(
        '[\'phone\']',
        '[\'addresses\'][0][\'phone\']',
        '[\'addresses\'][1][\'phone\']'
        );
    
    foreach ($arrayPaths as $path) {
        
        // hack to store/access multidimentional array keys as array, sets 
        // a variable named $phoneNumber
        $code = '$phoneNumber = $dataArray' . $path . ';';
        eval($code);
        var_dump($phoneNumber);
        
    }
dluptydi

dluptydi5#

解决这个问题最优雅的方法,是创建一个递归函数来获取值。下面是我的建议:

/**
 * Get value of given path of keys for a given multidimentional array in a recursive way.
 * @param array $array   A multidimentional array
 * @param array $key     A path of keys, example [1, 'name']
 * @param mixed $default What to return if path of keys does not exist in given array
 * @return mixed The found value, or the default value (can be any data type)
 */
function recursiveGetValue(array $array, array $key, $default=null) {
    $currentKey = current($key);
    if (!array_key_exists($currentKey, $array)) {
        return $default;
    }
    else if (count($key)==1) {
        return $array[$currentKey];
    }
    else {
        $restArray = $array[$currentKey];
        $restKey = array_slice($key, 1);
        return recursiveGetValue($restArray, $restKey, $default);
    }
}

$array = [
    'one'  =>['name'=>'Per', 'age'=>10],
    'two'  =>['name'=>'Pål', 'age'=>20],
    'three'=>['name'=>'Jan', 'age'=>15],
];

echo(recursiveGetValue($array, ['two', 'age']));
dly7yett

dly7yett6#

你必须为数组的每个维度使用一个单独的变量。你看到的多维数组的常见模式是这样的,你需要对第二维做一些事情:

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

    }

}

相关问题