1

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?

1 Answer 1

1

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
        )

)
Sign up to request clarification or add additional context in comments.

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.