在PHP的嵌套关联数组中搜索值并返回其路径 [英] Searching for a value and returning its path in a nested associative array in PHP
本文介绍了在PHP的嵌套关联数组中搜索值并返回其路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在PHP的嵌套关联数组中搜索值,类似于array_search但嵌套.我需要所有导致该特定值的键.
I'm trying to search for a value in a nested associative array in PHP, much like array_search but nested. I need all the keys leading to that particular value.
我在SO上没有看到任何要求该特定功能的帮助的内容,所以现在我要问.其他示例似乎返回数组中的所有值,而不仅仅是返回单个键/值对的路径.
I didn't see anything on SO asking for help with this specific function, so now I am asking. Other examples seem to return all values in an array, not just the path to a single key/value pair.
推荐答案
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的嵌套关联数组中搜索值并返回其路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文