从数组中获取值作为数组键

Get Value from Array as Array Key

如何从需要展开键的数组中递归获取值? 我知道,这个问题不好,让我解释一下。

我得到了一个数组

[
  "abc" => "def", 
  "hij" => [
              "klm" => "nop", 
              "qrs" => [
                          "tuv" => "wxy"
                       ]
           ]
]

所以,在函数内部,我传递:

function xget($section) {
    return $this->yarray["hij"][$section];
}

但是当我想用这个函数得到tuv值时,我想把section做成数组,例如:

要获得 hij.klm 值 (nop),我会做 xget('klm'),但要获得 hij.klm.qrs.tuv,我不能做 xget(['qrs', 'tuv']),因为 PHP 将 $section 视为键,并且不会递归地分解它。有什么方法可以不使用一些 ifs 和 $section[$i] ?

function xget($section) {
    return $this->yarray["hij"][$section];
}

那个是静态函数吧?

你也可以这样做

function xget($section) {
    if(isset($this->yarray["hij"][$section])){
         return $this->yarray["hij"][$section];
    }elseif(isset($this->yarray["hij"]["klm"]["qrs"][$section])){
         return $this->yarray["hij"]["klm"]["qrs"][$section];
    }
}

只要两者之间的键名不一样即可

无论嵌套结构如何,您都可以使用 array_walk_recursive 来查找 tuv 的值:

$tuv_val='';
function find_tuv($k,$v)
{
   global $tuv_val;
   if ($k=='tuv')
      $tuv_val=$v;
}
array_walk_recursive($this->yarray,"find_tuv");
echo "the value of 'tuv' is $tuv_val";

试试我的代码

<?php

    $array = array(
            'aaa' => 'zxc',
            'bbb' => 'asd',
            'ccc' => array(
                    'ddd' => 'qwe',
                    'eee' => 'tyu',
                    'fff' => array(
                                'ggg' => 'uio',
                                'hhh' => 'hjk',
                                'iii' => 'bnm',
                            ),
                ),
        );

    $find = '';

    function xget($key){
        $GLOBALS['find'] = $key;
        $find = $key;
        array_walk_recursive($GLOBALS['array'],'walkingRecursive');
    }


    function walkingRecursive($value, $key)
    {
        if ($key==$GLOBALS['find']){
            echo $value;
        }
    }


    xget('ggg');
?>