我在Laravel Collection类上遇到一些问题.
我正在尝试做的是:
>我有一个多站点解决方案,其中一个站点具有“促进者”.有时,一个促进者出现在多个站点上,而不仅仅是一个.
>我想在主页上列出所有协调人及其网站,但我不想有多个用户.
所以我现在要做的是:
>获取协调人.
>使用收集来收集帮助者并使用unique(‘name’).
这给了我独特的帮助者,但是只选择了它检测到的第一个,然后删除了其他的.
所以可以说我有这个集合:
Collection {
#items: array:3 [
0 => array:2 [
"name" => "John"
"site" => "Example"
]
1 => array:2 [
"name" => "Martin"
"site" => "Another"
]
2 => array:2 [
"name" => "John"
"site" => "Another"
]
]
}
使用unique()我将得到:
Collection {
#items: array:3 [
0 => array:2 [
"name" => "John"
"site" => "Example"
]
1 => array:2 [
"name" => "Martin"
"site" => "Another"
]
]
}
这就是我想要得到的:
Collection {
#items: array:3 [
0 => array:2 [
"name" => "John"
"site" => ["Example", "Another"]
]
1 => array:2 [
"name" => "Martin"
"site" => "Another"
]
]
}
有谁知道如何用Laravel的收藏课来做到这一点?
解决方法:
当卡在收藏夹中时,请始终记住reduce是您的工具库中的强大工具.
基于我无法解决的Sam的答案,我认为在groupBy上同时使用reduce应该可以…
$sites = collect([
["name" => "John", "site" => "Example"],
["name" => "Martin", "site" => "Another"],
["name" => "John", "site" => "Another"],
]);
$sites->groupBy('name')->reduce(function ($result, $item) {
$result[] = [
'name' => $item->first()['name'],
'sites' => $item->pluck('site')->toArray()
];
return $result;
}, collect([]))->toArray();
从控制台…
λ PHP artisan tinker
Psy Shell v0.8.2 (PHP 7.0.10 ÔÇö cli) by Justin Hileman
>>> $sites = collect([
... ["name" => "John", "site" => "Example"],
... ["name" => "Martin", "site" => "Another"],
... ["name" => "John", "site" => "Another"],
... ]);
=> Illuminate\Support\Collection {#698
all: [
[
"name" => "John",
"site" => "Example",
],
[
"name" => "Martin",
"site" => "Another",
],
[
"name" => "John",
"site" => "Another",
],
],
}
>>> $sites->groupBy('name')->reduce(function ($result, $item) {
... $result[] = ['name' => $item->first()['name'], 'sites' => $item->pluck('site')->toArray()];
...
... return $result;
... }, collect([]))->toArray();
=> [
[
"name" => "John",
"sites" => [
"Example",
"Another",
],
],
[
"name" => "Martin",
"sites" => [
"Another",
],
],
]
需要注意的一件事是,您在问题中指定如果只有一个站点,则站点应返回一个字符串,如果有多个站点,则应返回数组.以上解决方案不提供此功能!我认为这是不一致的,即使您只有一个值,也应该始终为sites键返回一个数组,因为这会使以后读取和操作变得更加困难.
但是,如果这很重要,则可以使用pluck设置数组时检查是否有很多站点,否则,可以将其设置为单个字符串,如下所示:
$sites->groupBy('name')->reduce(function ($result, $item) {
$result[] = [
'name' => $item->first()['name'],
'sites' => $item->pluck('site')->count() > 1 ? $item->pluck('site') : $item->first()['site']
];
return $result;
}, collect([]))->toArray();
会产生…
[
[
"name" => "John",
"sites" => [
"Example",
"Another",
],
],
[
"name" => "Martin",
"sites" => "Another",
],
]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。