Reputation: 747
With the following code:
$array = array( 'id' => '1', 'parent_id' => '0', 'name' => 'top level', 'children' => array( 'id' => '2', 'parent_id' => '1', 'name' => 'second level', 'children' => array( 'id' => '3', 'parent_id' => '2', 'name' => 'third level' ) ) ); function generateFlatArray($array){ $output .= '[select id="' . $array['id'] . '" name="' . $array['name'] . '"]'; if(is_array($array['children'])){ generateFlatArray($array['children']); } return $output; } print_r(generateFlatArray($array));
Why does this output:
[select id="1" name="top level"]
and not what I am expecting, which is:
[select id="1" name="top level"][select id="2" name="second level"][select id="3" name="third level"]
I hate recursion. I hate recursion. I hate recursion. Thanks.
Upvotes: 0
Views: 162
Reputation: 953
You did not use the return value of the function, only the first $output
is used.
function generateFlatArray($array){
$output .= '[select id="' . $array['id'] . '" name="' . $array['name'] . '"]';
if(is_array($array['children'])){
$output .= generateFlatArray($array['children']);
}
return $output;
}
Upvotes: 2
Reputation: 8400
Because you have to append the output during the recursive call as well:
if(is_array($array['children'])){
$output .= generateFlatArray($array['children']);
}
Upvotes: 1
Reputation: 324620
Because you aren't doing anything with the return value of the recursive steps.
$output .= generateFlatArray($array['children']);
That's what I think you want.
Upvotes: 1