亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如果鍵相同而不使用嵌套循環,則多維數組合并為一個數組

如果鍵相同而不使用嵌套循環,則多維數組合并為一個數組

PHP
陪伴而非守候 2023-04-28 15:17:12
 [      {        "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"      },我不想使用多個 foreach。提前致謝。
查看完整描述

2 回答

?
qq_笑_17

TA貢獻1818條經驗 獲得超7個贊

您可以使用以下代碼遞歸迭代所有結構并僅提取您需要的數據(按鍵)。我假設 $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);

    }

}


查看完整回答
反對 回復 2023-04-28
?
元芳怎么了

TA貢獻1798條經驗 獲得超7個贊

我不會使事情過于復雜,遍歷您的數據結構。將所有區域添加到集合中。準備您的數據結構,我添加了一個檢查以確保沒有重復項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()];


查看完整回答
反對 回復 2023-04-28
  • 2 回答
  • 0 關注
  • 145 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號