Dynamically accessing multidimensional array value

前端 未结 4 1619
长发绾君心
长发绾君心 2021-01-13 21:50

I\'m trying to find (or create) a function. I have a multidimensional array:

$data_arr = [
    \"a\" => [
        \"aa\" => \"abfoo\",
        \"ab\"          


        
4条回答
  •  执笔经年
    2021-01-13 22:27

    You can use this function that avoids the copy of the whole array (using references), is able to return a NULL value (using array_key_exists instead of isset), and that throws an exception when the path doesn't exist:

    function getItem(&$array, $path) {
        $target = &$array;
        foreach($path as $key) {
            if (array_key_exists($key, $target))
                $target = &$target[$key];
            else throw new Exception('Undefined path: ["' . implode('","', $path) . '"]');
        }
        return $target;
    }
    

    demo:

    $data = [
        "a" => [
            "aa" => "abfoo",
            "ab" => [
                "aba" => "abafoo",
                "abb" => NULL,
                "abc" => false
            ]
        ]
    ];
    
    var_dump(getItem($data, ['a', 'ab', 'aba']));
    # string(6) "abafoo"
    var_dump(getItem($data, ['a', 'ab', 'abb']));
    # NULL
    var_dump(getItem($data, ['a', 'ab', 'abc']));
    # bool(false)
    try {
        getItem($data, ['a', 'ab', 'abe']);
    } catch(Exception $e) {
        echo $e->getMessage();
    }
    # Undefined path: ["a","ab","abe"]
    

    Note that this function can be improved, for example you can test if the parameters are arrays.

提交回复
热议问题