I am fantasizing. We take data from the database to the $temp array, for example, as in the question
$temp = array( array('id' => 1, 'parent_id' => null), array('id' => 2, 'parent_id' => 1), array('id' => 3, 'parent_id' => 2), array('id' => 4, 'parent_id' => 2), array('id' => 5, 'parent_id' => 4), array('id' => 6, 'parent_id' => 4), array('id' => 7, 'parent_id' => 5), array('id' => 8, 'parent_id' => 5), );
Rearrange the array so that it is possible to access descendants by parent index:
$tree = array(); foreach ($temp as $row) { $tree[$row['parent_id']][] = $row['id']; }
Determine the function to draw the "twigs" from the root id
function printBranch($tree, $rootId, $prefix) { foreach ($tree[$rootId] as $branchId) { // Рисуем "листик" (в данном случае просто его id) echo($prefix . $branchId . "\n"); if (isset($tree[$branchId])) { // Если у этого "листика" есть "ответвление", рисуем его printBranch($tree, $branchId, $prefix . '__'); } } }
Draw the whole tree
printBranch($tree, '', '');
We get:
1 __2 ____3 ____4 ______5 ________7 ________8 ______6 [Finished in 0.3s]