-3

Assume I have multiple nested arrays (arrays of rows-arrays):

[
    ['name' => 'John', 'age' => 20],
    ['name' => 'Jack', 'age' => 30],
],
[
    ['salary' => 100],
    ['salary' => 200],
],

How do I merge the columns? Like this:

[
    ['name' => 'John', 'age' => 20, 'salary' => 100],
    ['name' => 'Jack', 'age' => 30, 'salary' => 200],
]

Upd. My research effort was: I've looked it in the web, in official docs and on SO - and haven't found an answer.

whyer
  • 783
  • 5
  • 16
  • 1
    It's not enough to create a question of *How do I...*, you are expected to show the effort you have made in the question. Just posting it to post an answer is not how this site works. – Nigel Ren Jan 24 '21 at 09:21
  • @NigelRen What exactly research effort do you mean? I haven't found the answer in official docs, neither on SO. What else should I do, can you advice? I hoped that someone else like me, when they will search it, could find it here - which I could not do because before this post there were no answer in web. – whyer Jan 24 '21 at 09:26
  • It's very similar to https://stackoverflow.com/questions/36807532/merging-two-php-arrays-with-same-numeric-key, but as this is a nested array, I haven't marked it as a duplicate. – Nigel Ren Jan 24 '21 at 09:30
  • @NigelRen in that question the row numbers have to be same - it's not just vertical merge, but vertical merge by row id - another thing. So, what else should I have do to show my research effort? – whyer Jan 24 '21 at 09:34
  • Your rows in both arrays have the same numeric keys - 0 and 1. – Nigel Ren Jan 24 '21 at 09:36

1 Answers1

2

Just use:

array_map('array_merge', ...$arrays)

- it performs array_merge against every row in your arrays, i.e. it first merges 1st rows with each other, then 2nd ones, 3rd ones and so on row by row.

whyer
  • 783
  • 5
  • 16
  • 3
    Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Syscall Jan 24 '21 at 09:40