[ "aa" => "abfoo", "ab" => [ -6ren">
gpt4 book ai didi

php - 动态访问多维数组值

转载 作者:行者123 更新时间:2023-12-04 16:04:50 24 4
gpt4 key购买 nike

我正在尝试查找(或创建)一个函数。我有一个多维数组:

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

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

最佳答案

尝试这个

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) ) ...在每次迭代中提供错误检查。

关于php - 动态访问多维数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36334635/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com