使用雄辩,我想用'Title'B从$ outputs数组中删除2个对象,并且只保留一个。
$ outputs具有以下信息:
[
{
"Title": "A",
"Publication date": "2013",
},
{
"Title": "B",
"Publication date": "2010",
},
{
"Title": "B",
"Publication date": "2999",
},
{
"Title": "B",
"Publication date": "5555",
},
];
我知道有很多关于此的文章,但我自己找不到办法。任何帮助将不胜感激。
答案 0 :(得分:1)
如果这是用于数组/集合,而不是用于Eloquent查询,则可以使用集合keyBy
方法来获取唯一值。
https://laravel.com/docs/5.8/collections#method-keyby
$data = [
[
"Title" => "A",
"Publication date" => "2013",
],
[
"Title" => "B",
"Publication date" => "2010",
],
[
"Title" => "B",
"Publication date" => "2999",
],
[
"Title" => "B",
"Publication date" => "5555",
],
];
$collection = collect($data)->keyBy('Title');
然后您的输出将如下所示:
Collection {#1389
#items: array:2 [
"A" => array:2 [
"Title" => "A"
"Publication date" => "2013"
]
"B" => array:2 [
"Title" => "B"
"Publication date" => "5555"
]
]
}
keyBy
方法将为您提供每个标题的集合中的最后一项,因此,如果您要获取特定项目,可以在调用keyBy
之前对集合进行排序:
// get each Title with the highest Publication date
$collection = collect($data)->sortBy('Publication date')->keyBy('Title');
// get each Title with the lowest Publication date
$collection = collect($data)->sortByDesc('Publication date')->keyBy('Title');
如果要返回不包含键“ A”和“ B”的数组,则可以执行以下操作:
$collection = collect($data)->keyBy('Title')->values()->toArray();
输出:
array:2 [
0 => array:2 [
"Title" => "A"
"Publication date" => "2013"
]
1 => array:2 [
"Title" => "B"
"Publication date" => "5555"
]
]
答案 1 :(得分:0)
您可以通过在查询中使用destinct
和groupBy
来做到这一点。