I have an array like this
Array
(
[0] => Array
(
[id] => 1 [children] => Array
(
[0] => Array
(
[id] => 2 [children] => Array
(
[0] => Array
(
[id] => 3 [children] => Array
(
[0] => Array
(
[id] => 4
)
)
)
)
)
)
)
[1] => Array (
[id] => 5
)
[2] => Array
(
[id] => 6
)
[3] => Array
(
[id] => 7
)
[4] => Array
(
[id] => 8
)
[5] => Array
(
[id] => 9
)
)
this is dynamically generated array i need a function that takes this array as input and returns each id with its parent id
as according to this array id 2 is child of id 1 and id 3 is child of id 3 and id 4 is child of id 3
and final result id 1 is parent of id 2 and id 2 is parent of id 3 and id 3 is parent of id 4 and ids 5-9 have no parents so they have 0 as default value
Beside the fact that you didn't come up with any effort by yourself, i'll post a solution anyway in case someone isn't aware of a solution with PHP's RecursiveIteratorIterator
Sample Data:
$arrData = [
[
'id' => 1,
'children' => [
'id' => 2,
'children' => [
'id' => 3,
'children' => [
'id' => 4
]
]
]
],
[
'id' => 5
],
[
'id' => 6
],
[
'id' => 7
],
[
'id' => 8
],
[
'id' => 9
],
];
Use of PHP's built int iterator classes
$arrDataConverted = [];
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($arrData));
foreach($iterator AS $key => $value)
{
$arrParentdata = $iterator->getSubIterator($iterator->getDepth()-1);
$arrItem = [
'id' => $value,
'parent' => (isset($arrParentdata['id'])) ? $arrParentdata['id'] : 0
];
$arrDataConverted[] = $arrItem;
}
print_r($arrDataConverted);