Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP hierarchical array - Parents and childs

I use PHP and mySQL with Idiorm. That might not be relevant.

My PHP array

  • It's a relationship between parents and childs.
  • 0 is the root parent.
  • Example: Root parent 0 have the child 33 which have the child 27 which have the child 71.

This array structure can be changed if needed for solving the problem.

array (   33 =>      array (       0 => '27',       1 => '41',   ),   27 =>      array (       0 => '64',       1 => '71',   ),   0 =>      array (       0 => '28',       1 => '29',       2 => '33',   ), ) 

My hierarchical result

Something like this, but as an array...

  0 =>        28       29       33          27 =>                64                71          41 

Information

  • The depth are unkown and it can be unlimited. I tried foreach, but it might not be the way.

My own thoughts

  • Some recursive function?
  • Some while loops?

I tried both of the above, just got a mess. It's a brainer.

like image 640
Jens Törnell Avatar asked Dec 14 '12 11:12

Jens Törnell


1 Answers

The suggestion by @deceze worked. However the input array needs to change a litte, like this...

$rows = array(     array(         'id' => 33,         'parent_id' => 0,     ),     array(         'id' => 34,         'parent_id' => 0,     ),     array(         'id' => 27,         'parent_id' => 33,     ),     array(         'id' => 17,         'parent_id' => 27,     ), ); 

From https://stackoverflow.com/a/8587437/476:

function buildTree(array $elements, $parentId = 0) {     $branch = array();      foreach ($elements as $element) {         if ($element['parent_id'] == $parentId) {             $children = buildTree($elements, $element['id']);             if ($children) {                 $element['children'] = $children;             }             $branch[] = $element;         }     }      return $branch; }  $tree = buildTree($rows);  print_r( $tree ); 
like image 187
Jens Törnell Avatar answered Sep 27 '22 19:09

Jens Törnell