Trying to figure out a way of getting the parent ID of an item in a multi dimensional array:
$Arr = array(
array(
"Id" => 1,
"Parent" => 0,
"Children" => array(
array(
"Id" => 2,
"Parent" => 1,
"Children" => array(),
),
array(
"Id" => 3,
"Parent" => 1,
"Children" => array(
array(
"Id" => 4,
"Parent" => 3,
"Children" => array(),
),
),
),
),
),
array(
"Id" => 5,
"Parent" => 0,
"Children" => array(
array(
"Id" => 6,
"Parent" => 5,
"Children" => array(),
),
),
)
);
I need to get the "Id" for the top element where "Parent" = 0. I.e. for the item with Id 4 it should return 1 as result, or a search for 6 would return 5. I have tried various ways of recursive function but only manage to get the correct result when the depth is 2.
I have found this function but it seems to return the name of the key rather than the value:
function find_parent($array, $needle, $parent = null) {
foreach ($array as $key => $value) {
if (is_array($value)) {
$pass = $parent;
if (is_string($key)) {
$pass = $key;
}
$found = find_parent($value, $needle, $pass);
if ($found !== false) {
return $found;
}
} else if ($key === 'Id' && $value === $needle) {
return $parent;
}
}
return false;
}
Edit
The following only works on the 1st level/depth:
function GetParent($Data = array(), $Needle = 0){
foreach($Data as $Key => $Item){
if($Item['Id'] === $Needle && $Item['Parent'] == 0){
return $Item['Id'];
}
if(sizeof($Item['Children']) !== 0)
GetParent($Item['Children'], $Item['Parent']);
}
return false;
}
I don't understand what I'm doing wrong.