Reputation: 43
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.
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.
Upvotes: 4
Views: 758
Reputation: 522382
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
// )
Upvotes: 3