Reputation: 13
I have an array that can vary in its dimension, sometimes can be small, sometimes can go deeper. I'm trying to search for a particular element in the array and if it is found, I would like to get a specific parent. So for instance, if I have an array as:
Again, the dimension can change, however, I'm looking for the the most outer parent's key that has siblings. (in this case)
Array (
[0] => Array (
[0] => Array (
[0] => Array ( <<----------------------------------------+
[0] => FOO0 |
[1] => BAR0 //Search BAR0 returns parent key 0 +
[2] => Array( |
[0] => HELLO0 |
[1] => BYE0 //Search BYE0 returns parent key 0 +
) |
[3] => FOO0 |
[4] => Array ( |
[0] => HELLO0 //Search HELLO0 returns parent key 0 --
)
)
[1] => Array ( <<----------------------------------------+
[0] => FOO1 |
[1] => BAR1 |
[2] => Array ( |
[0] => HELLO1 |
[1] => BYE1 |
) |
[3] => BASE1 |
[4] => Array ( |
[0] => BAZ1 |
[1] => Array ( |
[0] => DOO1 //Search DOO1 returns parent key 1 +
[1] => BOB2 //Search BOB2 returns parent key 1 +
)
)
)
[2] => FOO2 // Search FOO2 returns key 2 (itself)
)
)
)
Sample Output for FOO2
[2] => FOO2 // searched value
I would really appreciate some help! Thanks!
Upvotes: 1
Views: 3390
Reputation: 3804
function recursive_array_search($k,$h) {
foreach($h as $key=>$v) if($k===$v OR (is_array($v) && recursive_array_search($k,$v) !== false)) return $key;
return false;
}
Usage:
echo recursive_array_search($searchThis, $InThisArray);
Now you just have to modify this to return whatever you want.
Source: php.net
Upvotes: 0
Reputation: 48294
I'm not completely sure this is what you are looking for, but you can give it a try:
function find($needle, array $haystack)
{
foreach ($haystack as $i => $x) {
if (is_array($x)) {
$b = find($needle, $x);
if ($b) return count($haystack) > 1 ? array($i, $x) : $b;
}
else if ($x == $needle) {
return array($i, $x);
}
}
return false;
}
list($key, $val) = find('FOO1', $data);
This doesn't return the exact element, but a copy of it. If you want the original item, it will need to be updated to use references.
You can change array($i, $x)
to array($i => $x)
in both places if you don't want to use the list
construct when querying the function. But I think it's easier to work with as it is written.
Upvotes: 1