gpt4 book ai didi

php - 如何使用字符串作为数组索引路径来检索值?

转载 作者:可可西里 更新时间:2023-10-31 22:54:26 25 4
gpt4 key购买 nike

假设我有一个像这样的数组:

Array
(
[0] => Array
(
[Data] => Array
(
[id] => 1
[title] => Manager
[name] => John Smith
)
)
[1] => Array
(
[Data] => Array
(
[id] => 1
[title] => Clerk
[name] =>
(
[first] => Jane
[last] => Smith
)
)

)

)

我希望能够构建一个函数,我可以将一个字符串传递给该函数,该函数将充当数组索引路径并返回适当的数组值,而无需使用 eval()。这可能吗?

function($indexPath, $arrayToAccess)
{
// $indexPath would be something like [0]['Data']['name'] which would return
// "Manager" or it could be [1]['Data']['name']['first'] which would return
// "Jane" but the amount of array indexes that will be in the index path can
// change, so there might be 3 like the first example, or 4 like the second.

return $arrayToAccess[$indexPath] // <- obviously won't work
}

最佳答案

稍后,但是...希望对某人有所帮助:

// $pathStr = "an:string:with:many:keys:as:path";
$paths = explode(":", $pathStr);
$itens = $myArray;
foreach($paths as $ndx){
$itens = $itens[$ndx];
}

现在 itens 是您想要的数组的一部分。

[]的

实验室

关于php - 如何使用字符串作为数组索引路径来检索值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1677099/

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