Skip to content
Advertisement

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

 

i want to merge area into single array like


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

 

i don’t want to use multiple foreach. thanks in advance.

Advertisement

Answer

You can use the following code to recursively iterate of all your structure and extract only data you need (by key). I assume $data has your original data structure and within $result you will get array of area:

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

$result = [];
foreach ($it as $k => $v) {
    if ($k === 'area') {
        $result = array_merge($result, $v);
    }
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement