Stack Exchange
PHP - recursive array merge on a single tree structure, showing all permutations
I have a tree of data in a multi-dimensional array like this: 
[0] => Array
    (
        [0] => 14
        [1] => 12
        [2] => Array
            (
                [0] => Array
                    (
                        [0] => 16
                        [1] => 13
                    )

                [1] => Array
                    (
                        [0] => 13
                    )

                [2] => Array
                    (
                        [0] => 16
                    )

            )

    )

[1] => Array
    (
        [0] => 12
    )

...and I am trying to write an algorithm that outputs this:
[0] => Array
    (
        [0] => 14
        [1] => 12
        [2] => 16
        [3] => 13
    )

[1] => Array
    (
        [0] => 14
        [1] => 12
        [0] => 13
    )

[2] => Array
    (
        [0] => 14
        [1] => 12
        [0] => 16
    )

[3] => Array
    (
        [0] => 12
    )

The best way I can put it is a recursive array merge which shows all possible merged array permutations for all paths through a given tree of arrays. 
The closest I have managed is:
[0] => Array
    (
        [0] => 14
        [1] => 12
        [2] => 16
        [3] => 13
    )

[1] => Array
    (
        [0] => 13
    )

[2] => Array
    (
        [0] => 16
    )

[3] => Array
    (
        [0] => 12
    )

The code which outputs that is:
$return = [];

function enumerateTreePaths($arr, &$return, $path_k = 0)
{
    foreach ($arr as $el)
    {
        if (is_array($el))
        {
            foreach($el as $i)
            {
                enumerateTreePaths($i, $return, $path_k++);
            }
        }
        else
        {
            $return[$path_k][] = $el;
        }
    }
}

Apologies for careless naming conventions. Recursion == brain melt. 
I clearly need to do some sort of array merge in there, but have failed to work out the precise logic.
Thanks for any input.
Oh, that is actually wrapped in a foreach too;
    foreach ($trees as $tree)
    {
        $return = [];

        enumerateTreePaths($tree, $return);

        $paths = array_merge($paths, $return);
    }


Are duplicate values ignored while merging? For example value of [0][2][0][1][0] = 13 and value of [0][2][0][1][1] =13 too

there would always be 3 level tree OR could be deeper?

Could be deeper than 3.

Duplicates can be ignored, yes.

is array_merge_recursive what you are looking for?
