how to get the index of a children array for an array look like this:
Array
(
[1000] => Array
(
[firstName] => Ori
[lastName] => Smith
[children] => Array
(
[0] => 1001
[1] => 1002
[2] => 1003
[3] => 1004
[4] => 1005
[5] => 1006
[6] => 1007
[7] => 1008
[8] => 1009
[9] => 1010
)
)
)
so if I give 1009 as the search, it should return 1000.
It does not work with this code:
array_search($childrenId, array_column(myArray, 'children'));
You can use this function found here:
function getParentStack($child, $stack) {
foreach ($stack as $k => $v) {
if (is_array($v)) {
// If the current element of the array is an array, recurse it and capture the return
$return = getParentStack($child, $v);
// If the return is an array, stack it and return it
if (is_array($return)) {
return array($k => $return);
}
} else {
// Since we are not on an array, compare directly
if ($v == $child) {
// And if we match, stack it and return it
return array($k => $child);
}
}
}
// Return false since there was nothing found
return false;
}
I guess you could get the key by key(getParentStack(1009, $myarr))
or modify the function.
Try this
$result = array(
'1000'=>array('children'=>array('1001','1002')),
'2000'=>array('children'=>array('2001','2002'))
);
$searchValue = 2001;
$keyName = '';
foreach ($result as $key => $row) {
foreach ($row['children'] as $child) {
if ($child == $searchValue) {
$keyName = $key;
break;
}
}
}
echo $keyName;