Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading