How to access and manipulate multi-dimensional array by key names / path?

前端 未结 10 2199
北恋
北恋 2020-11-21 07:35

I\'ve to implement a setter in PHP, that allows me to specify the key, or sub key, of an array (the target), passing the name as a dot-separated-keys value.

10条回答
  •  礼貌的吻别
    2020-11-21 07:48

    If the keys of the array are unique, you can solve the problem in a few lines of code using array_walk_recursive:

        $arr = array('a' => 1,
            'b' => array(
                'y' => 2,
                'x' => array('z' => 5, 'w' => 'abc')
            ),
            'c' => null);
    
        function changeVal(&$v, $key, $mydata) {
            if($key == $mydata[0]) {
                $v = $mydata[1];
            }
        }
    
        $key = 'z';
        $value = '56';
        array_walk_recursive($arr, 'changeVal', array($key, $value));
    
        print_r($arr);
    

提交回复
热议问题