0

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.

3 Answers 3

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

Because you have to append the output during the recursive call as well:

if(is_array($array['children'])){
    $output .= generateFlatArray($array['children']);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.