I am trying to search a multidimensional array, where when I search for a value it should return me its parent key. Array looks like this:
[
"fruits" => [
"sweet" => [
"apple",
"banana",
],
"citrus" => [
"lemon",
"orange",
]
],
"vegetables" => [
"leafy" => [
"spinach",
"broccoli",
]
],
]
I want the function to return leafy
when I search for broccoli
or if I search for leafy
then it should return vegetables
but this function always return me null
:
function recursiveFind(array $haystack, $needle)
{
$foundKey = null;
foreach ($haystack as $key => $value) {
if(is_array($value)) {
if(in_array($needle, $value)){
return $key;
} else {
$foundKey = recursiveFind($value, $needle);
}
}
}
return $foundKey;
}
One more function I tried is as below, which returns me false
always:
function recursiveFind(array $haystack, $needle)
{
foreach($haystack as $key => $value) {
$current_key = $key;
if($needle === $value || (is_array($value) && recursiveFind($value, $needle) !== false)) {
return $current_key;
}
}
return false;
}
Above function works when there is only second level for example if we remove fruits and vegetable wrappers.