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

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

    Yet another solution for getter, using plain array_reduce method

    @AbraCadaver's solution is nice, but not complete:

    • missing optional separator parameter & split if required
    • it raises an error in case of trying to obtain a key from a scalar value like 'one.two' from ['one' => 2]

    My solution is:

    function get ($array, $path, $separator = '.') {
        if (is_string($path)) {
            $path = explode($separator, $path);
        }
    
        return array_reduce(
            $path,
            function ($carry, $item) {
                return $carry[$item] ?? null;
            },
            $array
        );
    }
    

    it requires PHP 7 due to ?? operator, but this can be changed for older versions pretty easy ...

提交回复
热议问题