【问题标题】:A simple way to get a single array containing all the integers that are contained within a nested object in PHP一种获取单个数组的简单方法,该数组包含 PHP 中嵌套对象中包含的所有整数
【发布时间】:2019-11-04 17:01:17
【问题描述】:

我有以下结构:

  {
    "produto_id" : 54,
    "descricao_id" : 25,
    "contas" : [
        {
            "marketplace_id" : 8,
            "contas_ids" : [
                 6, 8, 9
                ]
        },
        {
            "marketplace_id" : 9,
            "contas_ids" : [
                 44, 100
                ]
        }
        ]
}

我想得到一个包含所有“contas_ids”的数组,如下所示:

  [6, 8, 9, 44, 100]

我已经尝试过array_map,但我不得不使用这么多。使用 array_column 我实现了一些接近但它将输出分成几个数组。

 $ids = array_column($contas,  'contas_ids');

使用“dd”我明白了。

   array:2 [
  0 => array:3 [
    0 => 6
    1 => 8
    2 => 9
  ]
  1 => array:2 [
    0 => 44
    1 => 100
  ]
]

有人可以帮我生成一个包含所有“contas_id”的数组吗?

【问题讨论】:

  • @ggorlen 在我看来是有效的 JSON。
  • 你是对的。即便如此,尚不清楚$contas 是什么——它是完整的结构还是只是子数组?添加解析代码作为minimal reproducible example 的一部分会很有帮助。
  • @ggorlen 同意,看起来它只是 contas 数组。这就是我在回答中的假设。
  • 您提到使用 dd,这是在 Laravel 应用程序中吗?如果该数据来自查询,则可能有更好的方法来执行此操作。
  • 为什么这个json无效?我从一个发布请求中得到这个 json。

标签: php


【解决方案1】:

使用$ids = array_column($contas, 'contas_ids'); 获得子数组后,您可以使用array_merge 组合数组,如以下问题所述:Merge all sub arrays into one

call_user_func_array("array_merge", $ids);

【讨论】:

    【解决方案2】:

    这应该可以满足您的需求。

    $json = '{
        "produto_id" : 54,
        "descricao_id" : 25,
        "contas" : [{
            "marketplace_id" : 8,
            "contas_ids" : [ 6, 8, 9 ]
        },
        {
                "marketplace_id" : 9,
                "contas_ids" : [ 44, 100 ]
        }
        ]
    }
    ';
    
    $ids=[];
    foreach(json_decode($json,true)['contas'] as $key => $val){
        $ids = array_merge($ids, $val['contas_ids']);
    }
    var_dump($ids);
    

    【讨论】:

      【解决方案3】:

      还有一个array_merge() 解决方案,但这次是obscure operator

      <?php
      $json = '{
          "produto_id" : 54,
          "descricao_id" : 25,
          "contas" : [
              {
                  "marketplace_id" : 8,
                  "contas_ids" : [
                       6, 8, 9
                      ]
              },
              {
                  "marketplace_id" : 9,
                  "contas_ids" : [
                       44, 100
                      ]
              }
              ]
      }';
      $contas = json_decode($json, true);
      $ids = array_column($contas["contas"], "contas_ids");
      $integers = array_merge(...$ids);
      print_r($integers);
      

      输出:

      Array
      (
          [0] => 6
          [1] => 8
          [2] => 9
          [3] => 44
          [4] => 100
      )
      

      【讨论】:

        猜你喜欢
        • 2019-01-20
        • 2022-01-18
        • 2018-12-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多