使用相同的键合并和数组数组

Merging and array of arrays with the same keys

所以我找到了一个应该有效的答案,但它并没有出现...

Already accepted answer with the same issue.

我得到了以下名为 $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"
  ]
]

我阅读的答案建议 $all_banners = call_user_func_array('array_merge', $banners);

但是这给了我:

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

似乎只是替换而不是合并。有人有什么想法吗?

编辑

请阅读以下评论

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

所以我现在用另一个解决方案更新了我的代码,结果相同。

编辑 2

嗯,合并是合并而不是替换。所以我期望的是:

[
    "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" ]
]

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

$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 的有用行为从每个输入数组中取出一个元素,return 一个新的组合数组。