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

前端 未结 10 2219
北恋
北恋 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:56

    I have a really simple and dirty solution to this (really dirty! DO NOT use if the value of the key is untrusted!). It might be more efficient than looping through the array.

    function array_get($key, $array) {
        return eval('return $array["' . str_replace('.', '"]["', $key) . '"];');
    }
    
    function array_set($key, &$array, $value=null) {
        eval('$array["' . str_replace('.', '"]["', $key) . '"] = $value;');
    }
    

    Both of these functions do an eval on a snippet of code where the key is converted to an element of the array as PHP code. And it returns or sets the array value at the corresponding key.

提交回复
热议问题