There is an array:

$arr = array( // id parent_id text array(1, 0, 'text_1'), array(4, 2, 'text_4'), array(8, 0, 'text_8'), array(3, 1, 'text_3'), array(10, 3, 'text_10'), array(5, 4, 'text_5'), array(7, 3, 'text_7'), array(2, 1, 'text_2'), array(9, 0, 'text_9'), array(11, 0, 'text_11'), array(6, 4, 'text_6'), array(12, 11, 'text_12') ); 

It is necessary to draw the output of this array in the form of a tree in the following format:

 <div>text_1 <div>text_2 <div>text_4 <div>text_5 <div>text_6</div> </div> </div> 

I managed to build a tree. But it’s impossible to add divas and display them in sorted order. Tell me, please)) Code to form a tree:

 function tree(&$arr, $p_id = 0){ $out = []; //$arr[] = asort($arr); foreach($arr as $id => $node){ if($node[1] == $p_id) { $res = ['text' => $node[2], 'parent'=> $node[1]]; unset($arr[$id]); $children = tree($arr, $node[0]); if (count($children) > 0) $res['children'] = $children; $out[] = $res; } } return $out; } echo '<pre>'; print_r(tree($arr)); echo '</pre>'; 

Will return:

 Array ( [0] => Array ( [text] => text_1 [parent] => 0 [children] => Array ( [0] => Array ( [text] => text_3 [parent] => 1 [children] => Array ( [0] => Array ( [text] => text_10 [parent] => 3 ) [1] => Array ( [text] => text_7 [parent] => 3 ) ) ) ) ) [1] => Array ( [text] => text_8 [parent] => 0 ) [2] => Array ( [text] => text_9 [parent] => 0 ) [3] => Array ( [text] => text_11 [parent] => 0 [children] => Array ( [0] => Array ( [text] => text_12 [parent] => 11 ) ) ) ) 

    1 answer 1

     function print_tree($a, $level = 0){ foreach($a as $node){ echo "<div class='css_$level'>"; echo $node["text"]; if(isset($node["children"])){ print_tree($node["children"], $level + 1); } echo "</div>"; } } $t = tree($arr); print_tree($t); 
    • @ Mrak, With this tree f-tion returns errors ... Notice: Undefined index: text, Undefined index: children and so on - Eugene
    • Fixed a couple of mistakes - Mrak