【问题标题】:merge two arrays into one Laravel PHP [duplicate]将两个数组合并为一个 Laravel PHP [重复]
【发布时间】:2022-01-22 06:02:52
【问题描述】:

你好,我正在使用 laravel 中的集合和数组,现在我遇到了以下问题:在对数据集合进行分组后,结果如下:

    [
          [
             {
                "id":1,
                "number":1,
                "name":"ACTIVO",
                "type":1
             },
             {
                "id":2,
                "number":101,
                "name":"ACTIVO CORRIENTE",
                "type":1
             },
          ],
          [
             {
                "id":7,
                "number":2,
                "name":"PASIVO",
                "type":2
             }
          ]
       ]

我的问题是如何删除(或加入)内部数组并留下一个数组,如下所示

    [
        {
            "id":1,
            "number":1,
            "name":"ACTIVO",
            "type":1
        },
        {
            "id":2,
            "number":101,
            "name":"ACTIVO CORRIENTE",
            "type":1
        },
        {
            "id":7,
            "number":2,
            "name":"PASIVO",
            "type":2
        }
   ]

知道我该怎么做吗?

【问题讨论】:

  • 你能提供一些代码吗?

标签: php arrays laravel collections


【解决方案1】:
$yourArray = json_decode('[[{"id":1,"number":1,"name":"ACTIVO","type":1},{"id":2,"number":101,"name":"ACTIVO CORRIENTE","type":1}],[{"id":7,"number":2,"name":"PASIVO","type":2}]]', true);

$result = \array_merge(...$yourArray);

... - 解压所有内部数组,因为array_merge 接受可变数量的参数。所以基本上,您将每个内部数组作为 array_merge 的单独参数传递。阅读更多关于数组解包的信息here

JSON 字符串示例:http://sandbox.onlinephpfunctions.com/code/3f81e329250f7d4974c38453d024c320096d3f4c

【讨论】:

  • 修正这个错字:未定义的函数 'json_decde'。必须改为 json_decode
  • 谢谢,已修正错别字
  • 如果这是答案,请关闭大量重复的问题而不是回答。 stackoverflow.com/a/46861938/2943403
【解决方案2】:

根据您的数据集,这应该可以解决问题:

解决方案 1:

flatten()

flatten 方法将多维集合扁平化为 单一维度:

collect($data)->flatten(1)->all();

解决方案 2:

collapse()

collapse 方法将数组集合折叠成一个, 平面集合:

collect($data)->collapse()->all();

【讨论】:

    猜你喜欢
    • 2017-03-22
    • 2018-05-24
    • 2021-11-21
    • 2017-01-01
    • 2012-11-08
    • 1970-01-01
    • 2019-02-22
    • 1970-01-01
    • 2014-06-29
    相关资源
    最近更新 更多