ThomasB
ThomasB

Reputation: 17

PHP merging two arrays to create a new array

I am trying to create a new array using data from two arrays. I have tried array_merge, but I do not see the correct output

$a = array(array("c1"=>1,"c2"=>2),array("c1"=>7,"c2"=>9));
$b = array(array("d1"=>15,"d2"=>25),array("d1"=>71,"d2"=>92));

$result = array_merge_recursive($a, $b);
print_r($result);

This however does not produce the array that I require

Array
(
    [0] => Array
        (
            [c1] => 1
            [c2] => 2
        )

    [1] => Array
        (
            [c1] => 7
            [c2] => 9
        )

    [2] => Array
        (
            [d1] => 15
            [d2] => 25
        )

    [3] => Array
        (
            [d1] => 71
            [d2] => 92
        )

)

the output of the array I require is below

Array
(
    [0] => Array
        (
            [c1] => 1
            [c2] => 2
            [d1] => 15
            [d2] => 25
        )

    [1] => Array
        (
            [c1] => 7
            [c2] => 9
            [d1] => 71
            [d2] => 92
        )

)

Anyone able to assist?

Upvotes: 1

Views: 32

Answers (1)

rickdenhaan
rickdenhaan

Reputation: 11298

You can use array_map() to pass the array_merge() function to all items.

$a = array(array("c1"=>1,"c2"=>2),array("c1"=>7,"c2"=>9));
$b = array(array("d1"=>15,"d2"=>25),array("d1"=>71,"d2"=>92));

$result = array_map("array_merge", $a, $b);
print_r($result);

This will return the array you want:

Array
(
    [0] => Array
        (
            [c1] => 1
            [c2] => 2
            [d1] => 15
            [d2] => 25
        )

    [1] => Array
        (
            [c1] => 7
            [c2] => 9
            [d1] => 71
            [d2] => 92
        )

)

Upvotes: 1

Related Questions