fork(1) download
  1. <?php
  2. $datas=array(
  3. 'id' => 1,
  4. 'title'=>'book1',
  5. 'parentid'=>0
  6. ),
  7. 'id' => 2,
  8. 'title'=>'book2',
  9. 'parentid'=> 1
  10. ),
  11. 'id' => 3,
  12. 'title'=>'book3',
  13. 'parentid'=> 2
  14. ),
  15.  
  16. );
  17.  
  18. function buildTree($data,$prID=0,$q=NULL){
  19. $branch = array();
  20. foreach ($data as $key => $element) {
  21. $bool=!array_key_exists($element['parentid'], $data) && !$q;
  22. if($element['parentid']==$prID || $bool){
  23. $children = buildTree($data, $element['id'],TRUE);
  24. if ($children) {
  25. $element['children'] = $children;
  26. }
  27. $branch[] = $element;
  28. }
  29. }
  30. return $branch;
  31. }
  32.  
  33. function printTree($branch,$space=-1,$w=''){
  34. $q=0;
  35. if($w != ''){
  36. $w=$w.'-';
  37. }
  38. foreach ($branch as $value) {
  39. //$i=$space;
  40.  
  41. $q++;
  42. echo $w.$q.'-'.$value['title']."<br>";
  43. if(isset($value['children']) && is_array($value['children'])){
  44. $i=$i++;
  45. printTree($value['children'],$i,$w.$q);
  46. }
  47. }
  48. }
  49.  
  50. $ndata=buildTree($datas);
  51.  
  52. printTree($ndata);
  53.  
Success #stdin #stdout #stderr 0.02s 24448KB
stdin
Standard input is empty
stdout
1-book1<br>1-1-book2<br>1-1-1-book3<br>
stderr
PHP Notice:  Undefined variable: i in /home/ul74df/prog.php on line 47
PHP Notice:  Undefined variable: i in /home/ul74df/prog.php on line 47