0

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..

  • 1
    `array_combine($keys_array, $values_array)` – splash58 Jun 11 '22 at 10:33
  • Why post resolving advice as a comment? Were you going to close this question as a duplicate? – mickmackusa Jun 11 '22 at 12:55
  • Looks similar to https://stackoverflow.com/q/72546975/2943403 from 2 days ago. – mickmackusa Jun 11 '22 at 12:58
  • @mickmackusa I think you didn't carefully read my problem and the problem you identified as similar. this is not fair – Md Jahid Khan Limon Jun 12 '22 at 15:33
  • Look at [how incredibly accurate the duplicate page is](https://stackoverflow.com/a/72596825/2943403) at resolving your specific problem. I am confident that if you would have found that page before asking your question, you would have either solved your own problem without asking, or you would have posted a better failed coding attempt. – mickmackusa Jun 13 '22 at 00:43

1 Answers1

2

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
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55