Wednesday, 29 August 2018

Convert a multidimensional array to a set of nested sets

I am having a little problem i need some help with. Im trying to convert a multidimensional array into a flatten array with nested set values right and left like so:

    $array = {
         'id' => 1
         'name' => 'john'
         'childs' => array(
             array(
                 'id' => 1
                 'name' => 'jane'
             )
          )
    }

to
    $array = {
         array(
           'id' => 1,
           'name' => 'john'
           'left' => '1'
           'right' => '4'
         ),
         array(
           'id' => 1,
           'name' => 'jane'
           'left' => '2'
           'right' => '3'
         )
    }

Any help is appreciated!

function restructRecursive($array, $left = 1) {
  if (isset($array['childs'])) {
    $result = array();
    foreach ($array['childs'] as $child) {
      $result = array_merge($result, restructRecursive($child, $left+1));
    }
    unset($array['childs']);
  }
  $array['left'] = $left;
  return array_merge(array($array), $result);
}

$newStruct = restructRecursive($oldStruct);

0 comments:

Post a Comment