[英]Iterate over a collection in laravel and aggregate it
我有一个样本集
#items: array:4 [▼
0 => Collection {#465 ▼
#items: array:2 [▼
"id" => 1
"user_id" => 5
]
}
1 => Collection {#455 ▼
#items: array:2 [▼
"id" => 2
"user_id" => 5
]
}
2 => Collection {#419 ▼
#items: array:2 [▼
"id" => 3
"user_id" => 1
]
}
3 => Collection {#410 ▼
#items: array:2 [▼
"id" => 4
"user_id" => 1
]
}
]
}
如何将上述集合聚合到以下集合。 它是每个 user_id 的 id 计数。
#items: array:2 [▼
0 => Collection {#465 ▼
#items: array:2 [▼
"user_id" => 1
"count" => 2
]
}
1 => Collection {#455 ▼
#items: array:2 [▼
"user_id" => 5
"count" => 2
]
}
]
}
任何建议,将不胜感激。
我使用以下代码重新创建了该集合。
$collection = collect([
collect(['id' => 1, 'user_id' => 5]),
collect(['id' => 2, 'user_id' => 5]),
collect(['id' => 3, 'user_id' => 1]),
collect(['id' => 4, 'user_id' => 1]),
]);
假设这种结构,您可以通过链接几个方法来获得结果。
use Illuminate\Support\Collection;
$collection
->groupBy('user_id')
->map(fn ($item, $key) => ['user_id' => $key, 'count' => $item->count()])
->values();
// ->mapInto(Collection::class); // if you really need each item to be its own collection
或者,您可以运行:
$result = array_values($collection->reduce(function (array $carry, $item) {
$user_id = $item->first(fn($v, $k) => $k === "user_id");
if (array_key_exists($user_id, $carry)) {
$carry[$user_id]["count"]++;
} else {
$carry[$user_id] = [
"user_id" => $user_id,
"count" => 1,
];
}
return $carry;
}, []));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.