phparraysmultidimensional-arrayparent-childhierarchical-data

Convert a 2d array containing items with predefined depths into a nested parent-child array


Suppose I have this array:

[
    ['name' => 'ELECTRONICS', 'depth' => 0],
    ['name' => 'TELEVISIONS', 'depth' => 1],
    ['name' => 'TUBE', 'depth' => 2],
    ['name' => 'LCD', 'depth' => 2],
    ['name' => 'PLASMA', 'depth' => 2],
    ['name' => 'PORTABLE ELECTRONICS', 'depth' => 1],
    ['name' => 'MOBILE_PHONE', 'depth' => 2],
]

I want it to be converted into a multi-dimensional array such that immediate elements with a depth higher than the previous element will go inside the previous element with the key "children". like this:

Array
(
  [0] => Array
  (
    [name] => ELECTRONICS
    [depth] => 0
    [children] => Array
    (
      [0] => Array
      (
        [name] => TELEVISIONS
        [depth] => 1
        [children] => Array
        (
          [0] => Array
          (
            [name] => TUBE
            [depth] => 2
          )

          [1] => Array
          (
            [name] => LCD
            [depth] => 2
          )

          [2] => Array
          (
            [name] => PLASMA
            [depth] => 2
          )
        )
      )

      [1] => Array
      (
        [name] => PORTABLE ELECTRONICS
        [depth] => 1
      )
    )
  )
)

Solution

  • Here's my crack at it... Uses a foreach loop and an array of pointers to keep track of a bunch of different parent pointers.

    $multi_dimensional = array();
    $last_depth = 0;
    $parent = &$multi_dimensional;
    $parents[$last_depth] = &$parent;
    
    
    foreach ($start as $idx => $data) {
      // same/increasing depth
      if ($last_depth <= $data['depth']) {
        $parent['children'][] = $data;  
      } 
    
      // increasing depth
      if ($last_depth < $data['depth']) {
        $parents[$last_depth] = &$parent;
      }
    
      // decreasing depth
      if ($last_depth > $data['depth']) {
        $parent = &$parents[$data['depth']-1];
        $parent['children'][] = $data;  
      }
    
      // look ahead and prepare parent in increasing
      if (isset($start[$idx+1]) && $start[$idx+1]['depth'] > $data['depth']) {
        $last_insert_idx = count($parent['children'])-1;
        $parent = &$parent['children'][$last_insert_idx];
      }
      $last_depth = $data['depth'];
    }
    
    // initial values are in child "children" array
    $result = $multi_dimensional['children'];