0

I would like to merge two arrays in a way that values of first array are transformed in first elements of the subarray and values of the second array are transformed in second elements of the subarray. Here my example:

Array01
(
    [0] => 41558194
    [1] => 44677841
    [2] => 44503689
    [3] => 40651770
)

Array02
(
    [0] => 551
    [1] => 546
    [2] => 531
    [3] => 519
)

mergedArray
(
    [0] => Array([0] => 41558194 [1] => 551)
    [1] => Array([0] => 44677841 [1] => 546)
    [2] => Array([0] => 44503689 [1] => 531)
    [3] => Array([0] => 40651770 [1] => 519)
)

What is the most efficient way to do this? Many thanks in advance!

1
  • If they are same size, you can use only one foreach to do that Commented Oct 14, 2014 at 19:44

2 Answers 2

1

Here is a concise example using array_map:

function merge_arrays($a1, $a2) {
    return array($a1, $a2);
}

$result = array_map("merge_arrays", $arr, $arr2);
Sign up to request clarification or add additional context in comments.

Comments

0

An example with your values :

  $array1 = array(
        0 => 41558194,
        1 => 44677841,
        2 => 44503689,
        3 => 40651770
    );

    $array2 = array(
        0 => 551,
        1 => 546,
        2 => 531,
        3 => 519
    );


    $finalArray = array();

    foreach ($array1 as $key1 => $value1) {
        $finalArray[$key1] = array($value1, $array2[$key1]);
    }

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.