我快要疯了。
鉴于我有 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();
多谢你们!
蓝山帝景