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

前端 未结 10 2220
北恋
北恋 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条回答
  •  Happy的楠姐
    2020-11-21 08:10

    As a "getter", I've used this in the past:

    $array = array('data' => array('one' => 'first', 'two' => 'second'));
    
    $key = 'data.one';
    
    function find($key, $array) {
        $parts = explode('.', $key);
        foreach ($parts as $part) {
            $array = $array[$part];
        }
        return $array;
    }
    
    $result = find($key, $array);
    var_dump($result);
    

提交回复
热议问题