gpt4 book ai didi

php - 在 PHP 中的嵌套关​​联数组中搜索值并返回其路径

转载 作者:搜寻专家 更新时间:2023-10-31 21:08:40 24 4
gpt4 key购买 nike

我正在尝试在 PHP 中的嵌套关​​联数组中搜索值,这与 array_search 非常相似,但嵌套。我需要通向那个特定值的所有键。

我在 SO 上没有看到任何关于此特定功能的请求帮助,所以现在我要问了。其他示例似乎返回数组中的所有值,而不仅仅是单个键/值对的路径。

最佳答案

function array_search_path($needle, array $haystack, array $path = []) {
foreach ($haystack as $key => $value) {
$currentPath = array_merge($path, [$key]);
if (is_array($value) && $result = array_search_path($needle, $value, $currentPath)) {
return $result;
} else if ($value === $needle) {
return $currentPath;
}
}
return false;
}

$arr = [
'foo' => 'bar',
'baz' => [
'test' => 42,
'here' => [
'is' => [
'the' => 'path'
]
],
'wrong' => 'turn'
]
];

print_r(array_search_path('path', $arr));

// Array
// (
// [0] => baz
// [1] => here
// [2] => is
// [3] => the
// )

关于php - 在 PHP 中的嵌套关​​联数组中搜索值并返回其路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27151958/

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