0

I'm trying to create an array - in - array structure based on the value of each of the entries and I don't really know how I should approach this.

I hope someone from SO can help me achieve it efficiently.

Things I have tried until now: Setting parents and appending children, then doing the same for each of the children.

Input:

array(
  array('value' => 0),
  array('value' => 4),
  array('value' => 4),
  array('value' => 8),
  array('value' => 0),
  array('value' => 4)
)

Wanted Output

array(
  array('value' => 0
      'children' => array(
          array('value' => 4),
          array('value' => 4
              'children' => array(
                   array('value' => 8)
              )
          )
      )
  ),
  array('value' => 0
      'children' => array(
          array('value' => 4)
      )
  )
)

I'd appreciate any ideas. I'm thinking of a recursive method to achieve this, however I don't know how to do it properly.

Thank you very much in advance!

Grozav Alex Ioan
  • 1,559
  • 3
  • 18
  • 26

1 Answers1

1
function doit(&$a , &$i)
{
    $myval = $a[$i++]['value'];
    $chld = array();
    while( isset($a[$i]) && $a[$i]['value']>$myval )
    {
        $chld[]=doit($a ,$i);
    }
    if(count($chld)>0)
        return array('value'=>$myval,'children'=>$chld);
    else
        return array('value'=>$myval);
}

$a = array(
  array('value' => 0),
  array('value' => 4),
  array('value' => 4),
  array('value' => 8),
  array('value' => 0),
  array('value' => 4)
);

$i=0;
$result = array();
while(isset($a[$i]))
    $result[] = doit($a,$i);
print_r($result);

Please note, that pointer $i is passed as reference, that means it is the same variable through all recursion calls, always pointing to next unprocessed record.

One run of doit() function will process its one value and then (as long as there is a child candidate) will call itself recursively for each of its children.

David162795
  • 1,846
  • 3
  • 15
  • 20