我有一個有序的 laravel 集合,我也需要將 id = 20 的元素放在頂部,而不對其他元素進行排序。有可能與sortBy有關嗎?
uj5u.com熱心網友回復:
您可以嘗試使用filter方法
// Say $originalCollection is the response from the large request, with data from the database
$modifiedCollection = $originalCollection->filter(fn($item) => $item->id === 20)
->concat($originalCollection->filter(fn($item) => $item->id !== 20));
或者為了更直觀,您可以使用filter和reject方法
$modifiedCollection = $originalCollection->filter(fn($item) => $item->id === 20)
->concat($originalCollection->reject(fn($item) => $item->id === 20));
將$modifiedCollection在頂部有 id = 20 的記錄,其余記錄將保持與$originalCollection
uj5u.com熱心網友回復:
如果要將特定專案放在陣列的頂部,只需單獨添加即可。
$type = ['20' => '選擇型別'] $your_sorted_array ;
例子:
$country = ['1' => 'Andorra'] Countries::orderby('nicename')->pluck('name', 'id')->toArray();
編輯1:鑒于新資訊,您可以“手動”執行此操作的方法是在從集合構建陣列之后使用 unset 和 unshift 的組合。
$key_value = $country[20];
unset($country[20]);
array_unshift($country, $key_value );
uj5u.com熱心網友回復:
如果您的收藏不是很大,您可以使用keyBy、pull和prepend方法的組合
$originalCollection = Model::hereYourBigQuery()->get()->keyBy('id');
/*
now collection will look like this
{
'id1' => objectWithId1,
'id2' => objectWithId2,
...
20 => objectWithId20,
...
}
*/
// pull takes off element by its key
$toMakeFirst = $originalCollection->pull(20);
// prepend adding item into begining of the collection
// note that prepend will reindex collection so its keys will be set by default
$originalCollection->prepend($toMakeFirst);
upd:如果你想堅持排序,有一種方法
$collection = Model::yourBigQuery()->get();
$sorted = $collection->sort(function($a, $b){return $a->id == 20 ? -1 : 1;})->values();
如docs方法中所述,sort可以將閉包作為引數并在后臺使用php uasort
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/482688.html
上一篇:.htaccess規則匹配新url的一部分并用作舊url的查詢字串
下一篇:Python中的選擇排序就地作業
