Create tree from child node

I have an array with these elements:

array( array( 'id' => 1, 'name' => 'parent 1', 'parent_id' => null ), array( 'id' => 2, 'name' => 'child of parent 1', 'parent_id' => 1 ), array( 'id' => 3, 'name' => 'grand child of parent 1', 'parent_id' => 2 ), array( 'id' => 4, 'name' => 'parent 2', 'parent_id' => null ), array( 'id' => 5, 'name' => 'child of parent 2', 'parent_id' => 4 ), ); 

And my question is: how can I build a tree for a famous child? For example, if I know that the identifier is 3, I need to get an array of elements, including identifiers 1,2 and 3.

Thanks.

0
source share
1 answer

Maybe this is so:

 function build($tab, $id) { $res = array(); $node = $tab[$id]; $i = 0; do { $res[$i] = node; $node = $tab[$node['parent_id']]; $i++; } while( $node != null); return $res; } 
0
source

Source: https://habr.com/ru/post/1388305/


All Articles