如果键相同而不使用嵌套循环,则多维数组合并为一个数组

multidimensional array merge into one array if key is same without using nested loop


    [
      {
        "status": true,
        "data": [
          {
            "id": 2,
            "name": "Algeria",
            "country_code": "DZ",
            "regions": [
              {
                "id": 2,
                "country_id": 2,
                "region_code": "RG01",
                "depots": [
                  {
                    "id": 5,
                    "region_id": 2,
                    "depot_code": "DP04",
                    "depot_name": "North Depot",
                    "area": [
                      {
                        "id": 1,
                        "depot_id": 5,
                        "area_code": "AR1",
                        "area_name": "Area-1"
                      },
                      {
                        "id": 2,
                        "depot_id": 5,
                        "area_code": "AR2",
                        "area_name": "Area-2"
                      }
                    ]
                  },
                  {
                    "id": 6,
                    "region_id": 2,
                    "depot_code": "DP06",
                    "depot_name": "east Depot",
                    "area": [
                      {
                        "id": 3,
                        "depot_id": 6,
                        "area_code": "AR3",
                        "area_name": "Area-3"
                      }
                    ]
                  }
                ]
              },
              {
                "id": 3,
                "country_id": 2,
                "region_code": "RG02",
                "depots": []
              }
            ]
          }
        ]
      }
    ]

 

我想像

一样将区域合并成单个数组

    "area": [
      {
        "id": 1,
        "depot_id": 5,
        "area_code": "AR1",
        "area_name": "Area-1"
      },
      {
        "id": 2,
        "depot_id": 5,
        "area_code": "AR2",
        "area_name": "Area-2"
      },
      {
        "id": 3,
        "depot_id": 6,
        "area_code": "AR3",
        "area_name": "Area-3"
      }
    ]

 

我不想使用多个 foreach。 提前致谢。

我不会把事情复杂化,遍历你的数据结构。将所有区域添加到集合中。准备好你的数据结构,我添加了一个检查以确保没有 unique().

的重复项
$data = 'your-data';
$areas = collect();

foreach($data->data as $country) {
    foreach($country->regions as $region) {
        foreach ($region->depots as $depot) {
            $areas->concat($depot->area);
        }
    } 
}

$result = ['area' => $areas->unique('id')->all()];

您可以使用以下代码递归迭代所有结构并仅提取您需要的数据(按键)。我假设 $data 具有您的原始数据结构,并且在 $result 中您将获得区域数组:

$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($data), RecursiveIteratorIterator::SELF_FIRST);

$result = [];
foreach ($it as $k => $v) {
    if ($k === 'area') {
        $result = array_merge($result, $v);
    }
}