Question

How do I merge these associative arrays so that the indices ([0],[1]) are preserved and var_id, name and id are merged? I've tried array_combine and array_merge_recursive without succes.

Input

Array (
    [0] => Array (
        [var_id] => 43
    )
    [1] => Array (
        [var_id] => 25
    )
)
Array (
    [0] => Array (
        [name] => Tortoise
    )
    [1] => Array (
        [name] => Black
    )
)
Array (
    [0] => Array (
        [id] => 1907
    )
    [1] => Array (
        [id] => 1908
    )
)

Desired output

Array (
    [0] => Array (
        [var_id] => 43
        [name] => Tortoise
        [id] => 1907
    )
    [1] => Array (
        [var_id] => 25
        [name] => Black
        [id] => 1908
    )
)

Cheers,

Adnan

Était-ce utile?

La solution

Assuming your three arrays are called $array1, $array2, and $array3 here's a loop that will do what you want:

foreach(array($array1, $array2, $array3) AS $array) {
    foreach($array AS $key => $value) {
        foreach($value AS $subkey => $subvalue) {
            $final[$key][$subkey] = $subvalue;
        }
    }
}

Working example: http://3v4l.org/GY9oa

If you have an unknown number of input arrays to merge, it would be trivial to turn this into a function to handle that.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top