0

I'm stuck with a tree generating algorithm:

  • There's no parent-child params, only starting node value
  • Every node has 2 children (except the last children)

Array example:

$start = 1;
$depth = 3;

$s = array(

    'name'     => 1,                   // taken from $start
    'children' => array(

        array(
            'name'    => 2,
            'children => array(
                array( 'name' => 3 ),  /* No children for last node $depth */
                array( 'name' => 3 ),  /* No children for last node $depth */
            )
        ),

        array(
            'name'    => 2,
            'children => array(
                // same as above
            )
        ),

    )
);

At this point I've come up with a very ugly function and would appreciate any help or suggestions to build more nice algorithm.

Shader
  • 88
  • 8

1 Answers1

1

this should be helpful

function generateTree($depth, $level = 0)
{
    $result = array();
    if ($depth == $level) {
        $result = array('name' => $level);
    } else {
        $result = array('name' => $level, 'children' => array(generateTree($depth, $level + 1), generateTree($depth, $level + 1)));
    }
    return $result;
}

print_r(generateTree(3, 1));
Florin
  • 5,781
  • 2
  • 20
  • 30
laurent
  • 418
  • 3
  • 7