Laravel反转集合层次结构



假设我有一个像这样的集合:

$subscriptions = collect([
[
"id" => 1,
"event" => "FormCompleted",
"subscriber" => [
"id" => 2929,
"name" => "Adam",
"email" => "adam@dude.com"
]
],
[
"id" => 3,
"event" => "FormCompleted",
"subscriber" => [
"id" => 1928,
"name" => "Pope",
"email" => "pope@dude.com"
], 
],
[
"id" => 4,
"event" => "StatusChanged",
"subscriber" => [
"id" => 2929,
"name" => "Adam",
"email" => "adam@dude.com"
]
]
]);

显示了带有订阅者的事件列表。我想要的是重新分组,以显示订阅者列表及其事件。我如何对这些结果进行分组以得到这样的结果?

[
[
"id" => 2929,
"name" => "Adam",
"email" => "adam@dude.com",
"subscriptions" => [
[
"id" => 1,
"event" => "FormCompleted"
],
[
"id" => 4,
"event" => "StatusChanged"
],
]
],
[
"id" => 1928,
"name" => "Pope",
"email" => "pope@dude.com",
"subscriptions" => [
[
"id" => 3,
"event" => "FormCompleted"
]
]
]
]

这是我的代码…这是有效的,但它是非常混乱的,我觉得有一个更好的方法来做…

$subscribers = $subscriptions->groupBy('subscriber.id')
->map(function($group) {
$subscriber = $group[0]->subscriber;
$subscriber['subscriptions'] = $group->map(function($subscription) {
unset($subscription['subscriber']);
return $subscription;
});
return $subscriber;
})->values();

我认为这样应该返回所有具有组的订阅者,从而保证返回带有事件的非空订阅者更多细节请参阅文档

return Subscriber::has('groups')->get()->groupBy('id');

最新更新