【发布时间】:2017-08-05 20:47:22
【问题描述】:
我在使用 Laravel Collection 类时遇到了一些问题。
我想做的事:
- 我有一个多站点解决方案,其中一个站点有“促进者”。有时一位辅导员会出现在多个网站上,而不仅仅是一位。
- 我想在主页上列出所有促进者和他们所在的网站,但我不希望有多个用户。
所以我现在做的是:
- 获取引导者。
- 使用 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 的集合类来实现这一点吗?
【问题讨论】:
-
你为什么不使用
Group_concat?这可能会解决您的问题。 -
该站点未在数据库级别分配给用户。我正在遍历所有站点,找到它们的促进者,然后将站点名称添加到促进者对象中。我真的必须用这个集合来做这件事。基本上我要做的是:获取唯一但合并一个键。
-
尝试使用
GroupBy。这是示例。这可能会对您有所帮助。 laravel.com/docs/5.4/collections#method-groupby
标签: php arrays laravel laravel-5 collections