Question

I have a recursive function that does a lot of functioning and some database calls and what not to create some cool stuff. I want to save the results of each call to the function into an array.

So I did that, and I get a multidimensional array structured similarly to the results of the function in the first place. It looks like this:

Array
(
    [0] => 2507
    [1] => Array
        (
            [0] => 2508
        )

    [2] => 2073
    [3] => Array
        (
            [0] => 2397
        )
)

I can easily flatten this, using PHP 5.3's array_walk_recursive.

However, I would prefer that I didn't need to call another function after the original one, since that seems redundant.

How can I create a flat array from a recursive function that is "creating" the data with each call?

I have tried to truncate my recursive function a bit...

function get_children() {
    $leaf = new array();

    $results = database_call();
    foreach($results as $res) {
        $leaf[] = $res;

        // do tons of stuff not included
        if($res->children == 1) {   
           $leaf[] = get_children();
        }
    }
return $leaf;
}

$i_wish_this_was_flat = get_children();
Was it helpful?

Solution

Maybe you can use

$leaf = array_merge($leaf, get_children());

instead of

$leaf[] = get_children();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top