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

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

如何在 Laravel 集合合并中保留嵌套數組

如何在 Laravel 集合合并中保留嵌套數組

PHP
森林海 2023-04-21 09:56:05
我快要瘋了。鑒于我有 2 個數組$array1 = [    "data_to_merge" => ["2020-03-11 16:00:00", "2020-03-24 14:00:00"],    "data_to_merge_past_year" => ["2019-03-11 16:00:00"],];$array2 = [    "data_to_merge" => [],    "data_to_merge_past_year" => ["2018-03-11 14:00:00"],];我的目標是得到這樣的結果all: [       "data_to_merge" => [         "2020-03-11 16:00:00",         "2020-03-24 14:00:00"       ],       "data_to_merge_past_year" => [         "2018-03-11 14:00:00",         "2018-03-11 16:00:00",       ],     ],我試過簡單的$result = collect($array1)->merge(collect($array2));但是通過這種方法,它將從我的第一個數組中刪除值data_to_merge。有什么 Laravel 方法可以得到那個結果嗎?它可以超過 2 個數組,只是為了演示。這是我的完整示例,基本上是一樣的$array1 = [    "host" => "blablubb",    "data_to_merge" => [      "2020-03-11 16:00:00",      "2020-03-24 14:00:00"    ],    "data_to_merge_past_year" => [      "2019-03-11 16:00:00"    ],];$array2 = [    "host" => "blablubb",    "data_to_merge" => [],    "data_to_merge_past_year" => [      "2018-03-11 16:00:00"    ],];$array3 = [    "host" => "blablubb",    "data_to_merge" => [],    "data_to_merge_past_year" => [],];$array4 = [    "host" => "blablubb",    "data_to_merge" => [      "2020-03-04 14:00:00",      "2020-03-04 17:00:00"    ],    "data_to_merge_past_year" => [],];$all = collect([$array1, $array2, $array3, $array4]);$all    ->groupBy('host')    ->map(function ($item) {        if (count($item) > 1) {            $result = collect([]);            foreach ($item as $subItem) {                $result = $result->merge($subItem);            }            return $result;        }        return $item->first();    })    ->values()    ->toArray();多謝你們!
查看完整描述

1 回答

?
藍山帝景

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

您可以為此使用mergeRecursive :

$array1 = [

? ? "data_to_merge" => ["2020-03-11 16:00:00", "2020-03-24 14:00:00"],

? ? "data_to_merge_past_year" => ["2019-03-11 16:00:00"],

];


$array2 = [

? ? "data_to_merge" => [],

? ? "data_to_merge_past_year" => ["2018-03-11 14:00:00"],

];


$result = collect($array1)->mergeRecursive(collect($array2));

結果:


Illuminate\Support\Collection {#1278 ▼

? #items: array:2 [▼

? ? "data_to_merge" => array:2 [▼

? ? ? 0 => "2020-03-11 16:00:00"

? ? ? 1 => "2020-03-24 14:00:00"

? ? ]

? ? "data_to_merge_past_year" => array:2 [▼

? ? ? 0 => "2019-03-11 16:00:00"

? ? ? 1 => "2018-03-11 14:00:00"

? ? ]

? ]

}

從文檔:


mergeRecursive 方法將給定的數組或集合遞歸地與原始集合合并。如果給定項中的字符串鍵與原始集合中的字符串鍵匹配,則這些鍵的值將合并到一個數組中,這是遞歸完成的:


$collection = collect(['product_id' => 1, 'price' => 100]);


$merged = $collection->mergeRecursive(['product_id' => 2, 'price' => 200, 'discount' => false]);


$merged->all();


// ['product_id' => [1, 2], 'price' => [100, 200], 'discount' => false]


查看完整回答
反對 回復 2023-04-21
  • 1 回答
  • 0 關注
  • 155 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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