I'm trying to get a multidimensional array comparing the [id] values with the [parent_id] values from an array like this:
Array
(
[0] => Array
(
[id] => 101
[title] => parent_101
[parent_id] => 0
[level] => 1
)
[1] => Array
(
[id] => 118
[title] => parent_118
[parent_id] => 0
[level] => 1
)
[2] => Array
(
[id] => 119
[title] => child_119
[parent_id] => 118
[level] => 2
)
[4] => Array
(
[id] => 173
[title] => subchild_173
[parent_id] => 119
[level] => 3
)
[5] => Array
(
[id] => 120
[title] => child_120
[parent_id] => 118
[level] => 2
)
[6] => Array
(
[id] => 145
[title] => deeperchild_145
[parent_id] => 173
[level] => 4
)
)
The result should be a new array like this:
Array
(
[0] => Array
(
[title] => parent_101
[id] => 101
[parent_id] => 1
[level] => 1
[childrens] => Array
(
)
)
[1] => Array
(
[id] => 118
[title] => parent_118
[parent_id] => 1
[level] => 1
[childrens] => Array
(
[0] => Array
(
[id] => 119
[title] => child_119
[parent_id] => 118
[level] => 2
[deeper] => Array
(
[0] => Array
(
[id] => 173
[title] => subchild_173
[parent_id] => 119
[level] => 3
[deeperchild] => Array
(
[id] => 145
[title] => deeperchild_145
[parent_id] => 173
[level] => 4
)
)
)
)
[1] => Array
(
[id] => 120
[title] => parent_120
[parent_id] => 118
[level] => 2
[deeper] => Array
(
)
)
)
)
)
so far I come up with this code but I'm stuck at the 3rd level deeper and I was wondering if there is a better way to do that.
> $parentsitms = array(); $deeperArr = array(); $childsArr = array();
> $childparent = array(); $menu = array();
>
> foreach ($list as $items) {
>
> if($items->level==='1'):
> $idparent = $items->id;
> $parents = $items->title;
> $parentsitms[] = ['id'=>$items->id,'title'=>$items->title,'parent_id'=>$items->parent_id,'level'=>$items->level];
>
> endif;
>
> }
> foreach ($parentsitms as $menuitm) {
> $parents = $menuitm;
>
> foreach($list as $chd){
>
> if($menuitm['id'] === $chd->parent_id):
> $childparent = $chd->id;
> $childsItms = ['id'=>$chd->id,'title'=>$chd->title,'parent_id'=>$chd->parent_id,'level'=>$chd->level];
> $childsArr[] = [array_merge($childsItms,array('deeper'=>array()))];
> endif;
>
> if($childparent === $chd->parent_id):
> $array = ['title'=>$chd->title,'id'=>$chd->id,'parent_id'=>$chd->parent_id,'level'=>$chd->level];
> $deeperArr[] = ['id'=>$chd->id,'title'=>$chd->title,'parent_id'=>$chd->parent_id,'level'=>$chd->level];
> $childsArr = [array_merge($childsItms,array('deeper'=>$deeperArr))];
> endif;
>
> ######## can't get the 4th level deeper ######
>
>
> }
>
> $menu[] = array_merge($parents,array('childrens'=>$childsArr));
> }
>
> echo '<pre>'; print_r($menu);
Any help is very appreciated.
>prefixes in the code, they make it impossible to execute.