php – Combine multiple array into single multi-dimension array and assign key

Issue

What is the simpliest way to do merge multiple array values into a single multi-dimension array. For example, I have several arrays ($arr_a, $arr_b) like,

Array
(
    [0] => a1
    [1] => a2
    [2] => a3
)

Array
(
    [0] => b1
    [1] => b2
    [2] => b3
)

The keys array ($keys) for new array like

Array
(
    [0] => key1
    [1] => key2
    [2] => key3
)

I want combine these array to a single array with keys like

Array
(
    [0] => Array
        (
            [key1] => a1
            [key2] => a2
            [key3] => a3
        )

    [1] => Array
        (
            [key1] => b1
            [key2] => b2
            [key3] => b3
        )

)

I tried this this code

$ouput = array_map(null, $arr_a, $arr_b);

But I can’t add array keys by this code..

Solution

To combine each array with the keys, you can use something like array_combine() which can take your keys array and add them to the value array.

To apply this and combine the array, using array_map() with array_combine as the callback makes it possible with combining the two arrays as well. Using arrow functions also means you don’t have to worry about the scope of the keys array..

$arr_a = ['a1', 'a2', 'a3'];
$arr_b = ['b1', 'b2', 'b3'];

$keys = ['key1', 'key2', 'key3'];

print_r(array_map(fn ($arr) => array_combine($keys, $arr), [$arr_a, $arr_b]));

gives…

Array
(
    [0] => Array
        (
            [key1] => a1
            [key2] => a2
            [key3] => a3
        )

    [1] => Array
        (
            [key1] => b1
            [key2] => b2
            [key3] => b3

Answered By – Nigel Ren

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published