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

前端 未结 10 2206
北恋
北恋 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

    I have solution for you not in the pure PHP, but using ouzo goodies concretely Arrays::getNestedValue method:

    $arr = array('a' => 1,
        'b' => array(
            'y' => 2,
            'x' => array('z' => 5, 'w' => 'abc')
        ),
        'c' => null);
    
    $key = 'b.x.z';
    $path = explode('.', $key);
    
    print_r(Arrays::getNestedValue($arr, $path));
    

    Similarly if you need to set nested value you can use Arrays::setNestedValue method.

    $arr = array('a' => 1,
        'b' => array(
            'y' => 2,
            'x' => array('z' => 5, 'w' => 'abc')
        ),
        'c' => null);
    
    Arrays::setNestedValue($arr, array('d', 'e', 'f'), 'value');
    print_r($arr);
    

提交回复
热议问题