test1 - PHP Online

Form of PHP Sandbox

Enter Your PHP code here for testing/debugging in the Online PHP Sandbox. As in the usual PHP files, you can also add HTML, but do not forget to add the tag <?php in the places where the PHP script should be executed.



Your result can be seen below.

Result of php executing





Full code of test1.php

  1. <?php
  2. $datas = array(
  3.     array('id' => 1, 'parent_id' => 0, 'name' => 'Parent 1'),
  4.     array('id' => 2, 'parent_id' => 1, 'name' => 'Child 1.1'),
  5.     array('id' => 3, 'parent_id' => 2, 'name' => 'Child with child 1.1.1'),
  6.     array('id' => 4, 'parent_id' => 2, 'name' => 'Child with child 1.1.2'),
  7.     array('id' => 5, 'parent_id' => 4, 'name' => 'Child with child of child 1.1.2.1'),
  8.     array('id' => 5, 'parent_id' => 1, 'name' => 'Child 1.2'),
  9.     array('id' => 6, 'parent_id' => 5, 'name' => 'Child with child 1.2.1'),
  10.     array('id' => 7, 'parent_id' => 5, 'name' => 'Child with child 1.2.2'),
  11.     array('id' => 8, 'parent_id' => 5, 'name' => 'Child with child 1.2.3'),
  12.     array('id' => 9, 'parent_id' => 0, 'name' => 'Parent 2'),
  13.     array('id' => 10, 'parent_id' => 9, 'name' => 'Child 2.1'),
  14.     array('id' => 11, 'parent_id' => 9, 'name' => 'Child 2.2'),
  15.     array('id' => 12, 'parent_id' => 11, 'name' => 'Child with child 2.2.1'),
  16.     array('id' => 13, 'parent_id' => 11, 'name' => 'Child with child 2.2.2'),
  17.     array('id' => 14, 'parent_id' => 0, 'name' => 'Parent 3'),
  18.     array('id' => 15, 'parent_id' => 14, 'name' => 'Child 3.1'),
  19.     array('id' => 16, 'parent_id' => 15, 'name' => 'Child with child 3.1.1'),
  20.     array('id' => 17, 'parent_id' => 15, 'name' => 'Child with child 3.1.2')
  21.     );
  22.  
  23. function generatePageTree($datas, $parent = 0, $depth = 0) {
  24.     $ni=count($datas);
  25.     if($ni === 0 || $depth > 1000) return ''; // Make sure not to have an endless recursion
  26.     $tree = '<ul>';
  27.     for($i=0; $i < $ni; $i++){
  28.         if($datas[$i]['parent_id'] == $parent){
  29.             $tree .= '<li>';
  30.             $tree .= $datas[$i]['name'];
  31.             $tree .= generatePageTree($datas, $datas[$i]['id'], $depth+1);
  32.             $tree .= '</li><br/>';
  33.         }
  34.     }
  35.     $tree .= '</ul>';
  36.     return $tree;
  37. }
  38.  
  39. //echo(generatePageTree($datas));
  40. var_dump(generatePageTree($datas));
File Description
  • test1
  • PHP Code
  • 22 Aug-2022
  • 1.85 Kb
You can Share it: