Merging and array of arrays with the same keys

时间:2018-12-03 13:16:49

标签: php array-merge

So I found an answer which is supposed to work, however it doesn't appear too...

Already accepted answer with the same issue.

I have got the following array called $banners:

[
  0 => [
    "bannerCustomTemplate" => 0,
    "bannerId" => 1,
    "bannerType" => 1,
    "bannerTitle" => "Merry",
    "bannerStrapline" => "Christmas",
    "bannerPeriod" => "2018-12-01 to 2018-12-10",
    "bannerText" => "Christmas opening hours"
  ],
  1 => [
    "bannerCustomTemplate" => 0,
    "bannerId" => 7,
    "bannerType" => 2,
    "bannerTitle" => "Easter",
    "bannerStrapline" => "Test",
    "bannerPeriod" => "2018-12-04 to 2018-12-12",
    "bannerText" => "dsadasdaas"
  ]
]

The answers I have read suggest $all_banners = call_user_func_array('array_merge', $banners);.

However this is giving me:

[
  "bannerCustomTemplate" => 0,
  "bannerId" => 7,
  "bannerType" => 2,
  "bannerTitle" => "Easter",
  "bannerStrapline" => "Test",
  "bannerPeriod" => "2018-12-04 to 2018-12-12",
  "bannerText" => "dsadasdaas"
]

Seems like it's just replacing rather than merging. Anyone got any ideas?

Edit

Just read the following comment

Little note here. The updated variant with unpacking array doesn't work with string keys. But the first one works perfect. Just keep in mind this. – Alliswell

So I have now updated my code with another solutions, with the same results.

Edit 2

Well, merging is merging not replacing. So what I expect is:

[
    "bannerCustomTemplate" => [ 0, 0 ],
    "bannerId" => [ 1, 7 ],
    "bannerType" => [ 1, 2 ],
    "bannerTitle" => [ "Merry", "Easter" ]
    "bannerStrapline" => [ "Christmas", "Test" ]
    "bannerPeriod" => [ "2018-12-01 to 2018-12-10", "2018-12-04 to 2018-12-12" ]
    "bannerText" => ["Christmas opening hours", "dsadasdaas" ]
]

1 个答案:

答案 0 :(得分:1)

如果已知所有数组都以相同的顺序包含相同的键,则这可能是最简单的:

$data = [
    ['foo' => 'bar', 'baz' => 42],
    ['foo' => 'baz', 'baz' => 69]
];

$result = array_combine(array_keys($data[0]), array_map(null, ...$data));

这使用array_map with null as the callback的有用行为来从每个输入数组中获取一个元素并返回一个新的组合数组。