动态访问多维数组值

时间:2016-03-31 13:17:43

标签: php function multidimensional-array

我试图找到(或创建)一个函数。我有一个多维数组:

$data_arr = [
    "a" => [
        "aa" => "abfoo",
        "ab" => [
            "aba" => "abafoo",
            "abb" => "abbfoo",
            "abc" => "abcfoo"
        ],
        "ac" => "acfoo"
    ],
    "b" => [
        "ba" => "bafoo",
        "bb" => "bbfoo",
        "bc" => "bcfoo"
    ],
    "c" => [
        "ca" => "cafoo",
        "cb" => "cbfoo",
        "cc" => "ccfoo"
    ]
];

我想使用单维数组访问一个值,如下所示:

$data_arr_call = ["a", "ab", "abc"];

someFunction( $data_arr, $data_arr_call ); // should return "abcfoo"

这似乎已经是这类事情的功能,我只是不知道要搜索什么。

4 个答案:

答案 0 :(得分:4)

试试这个

function flatCall($data_arr, $data_arr_call){
    $current = $data_arr;
    foreach($data_arr_call as $key){
        $current = $current[$key];
    }

    return $current;
}

OP的说明:

$current变量以迭代方式构建,如下所示:

flatCall($data_arr, ['a','ab','abc']);

1st iteration: $current = $data_arr['a'];
2nd iteration: $current = $data_arr['a']['ab'];
3rd iteration: $current = $data_arr['a']['ab']['abc'];

您还可以在每次迭代中执行if ( isset($current) ) ...以提供错误检查。

答案 1 :(得分:0)

你需要这样的功能:

function getValue($data_arr, $data_arr_call) {
    foreach ($data_arr_call as $index) {
        if (isset($data_arr[$index])) {
            $data_arr = $data_arr[$index];
        } else {
            return false;
        }
    }
    return $data_arr;
}

并像这样使用它:

$data_arr = [
    "a" => [
        "ab" => [
            "abc" => "abbfoo",
        ],
    ],
];
$data_arr_call = ["a", "ab", "abc"];
$value = getValue($data_arr, $data_arr_call);
if ($value) {
    // do your stuff
}

答案 2 :(得分:0)

你可以使用这个函数来避免整个数组的副本(使用引用),能够返回一个NULL值(使用array_key_exists而不是isset),并且当抛出异常时路径不存在:

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;
}

演示:

$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"]

请注意,可以改进此功能,例如,您可以测试参数是否为数组。

答案 3 :(得分:0)

想发布一个更优雅的解决方案:array_reduce

    $data_arr = [
        "a" => [
            ...
            "ab" => [
                ...
                "abc" => "abcfoo"
            ],
            ...
        ],
        ...
    ];

    $result = array_reduce(["a", "ab", "abc"], function($a, $b) {
        return $a[$b];
    }, $data_arr);

    // returns "abcfoo"

最近,我在更新一些旧代码到ES6时一直使用Javascript Array.reduce()

JS:
const data_obj = {...};
let result = ['a','ab','abc'].reduce((a, b) => a[b], data_obj);