本文介紹了Laravel eloquent 集合上的 Array_unique的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
不確定這是否可行,但我嘗試在我擁有的一組項目上運行 array_unique,以刪除重復項.雖然我無法讓它工作.
Not sure if this is possible but im trying to run array_unique over a collection of items i have, to remove duplicates. Although i cannot get it working.
我的控制器邏輯:
// init models
$jobs = Job::search();
$countries = $jobs->get()->map(function( $job ) {
return $job->country;
});
$countries = array_unique( $countries->toArray() );
雖然這會得到數組到字符串的轉換"錯誤
although this gets a "Array to string conversion" error
推薦答案
您可以使用 distinct
或 group by
在您的選擇子句中.但是,如果您真的需要在對象數組上具有唯一值,您可以執行以下操作:
You can have unique values in your DB results using distinct
or group by
in your select clause. But, if you really need to have unique values over an array of object you can do the following:
$uniques = array();
foreach ($countries as $c) {
$uniques[$c->code] = $c; // Get unique country by code.
}
dd($uniques);
這篇關于Laravel eloquent 集合上的 Array_unique的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!