【问题标题】:How to merge an associative array into a single associative row of a multidimensional array?如何将关联数组合并为多维数组的单个关联行?
【发布时间】:2016-09-28 18:20:08
【问题描述】:

我有这两个数组:

array1[1]["associativeKey1"]
         ["associativeKey2"]
      [2]["associativeKey1"]
         ["associativeKey2"]
...

array2["associative"]

我为 array1 中的每个数字生成一个 array2,而不是 associativeKey,只有数字。 我想合并这样的:

array1[1]["associativeKey1"]["associativeKey2"][content of array2 with all its keys]
      [2]["associativeKey1"]["associativeKey2"][content of array2 with all its keys]

你能帮帮我吗? 非常感谢!

【问题讨论】:

  • 有很多方法可以做到这一点。为什么不给我们展示一个真实的案例场景呢?最好解释一下如何做以及为什么做。

标签: php


【解决方案1】:

如果我理解正确,您可以为 array1 的每个顶级元素调用 arra-merge

foreach ($array1 as &$item) {
   $item = array_merge($item, $array2);

【讨论】:

    【解决方案2】:

    您应该尝试使用array_values(仅在非递归的情况下)

    【讨论】:

    • 对于递归替代方案,还有另一个 answer here
    猜你喜欢
    • 1970-01-01
    • 2011-11-26
    • 1970-01-01
    • 2013-11-24
    • 2018-04-18
    • 2020-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多