[英]Laravel collections not sorting
我有以下Eloquent系列:
[
[
'id' => 60902,
'source' => 'M',
'price' => 10.15
],
[
'id' => 57348,
'source' => 'A',
'price' => 12.00
],
[
'id' => 54472,
'source' => 'A',
'price' => 12.00
],
]
我正在嘗試使用此代碼對其進行排序:
$items = $items->sort(function (Item $a, Item $b) {
if ($a->source == 'A') {
if ($b->source == 'M' || ($b->source == 'A' && $a->price < $b->price)) {
return 1;
} elseif ($b->source == 'A' && $a->price == $b->price) {
return 0;
} else {
return -1;
}
} else {
if ($b->source == 'A' || ($b->source == 'M' && $b->price < $a->price)) {
return -1;
} elseif ($b->source == 'M' && $b->price == $a->price) {
return 0;
} else {
return 1;
}
}
});
但是, $items
的原始排序順序在前后總是相同的。 列表中的第一個項目(60902)應該從開頭移動到結尾。
我運行了一個Xdebug跟蹤,可以看到項目60902在排序函數中返回-1
,而另外兩個項目返回0
因為它們彼此相同。
這就是我期望集合在排序后的樣子:
[
[
'id' => 57348,
'source' => 'A',
'price' => 12.00
],
[
'id' => 54472,
'source' => 'A',
'price' => 12.00
],
[
'id' => 60902,
'source' => 'M',
'price' => 10.15
]
]
我的邏輯在哪里搞砸了?
對此的解決方案非常簡單......我只需要在返回排序值時交換1
和-1
以獲得我想要的結果。
新代碼如下所示:
$items = $items->sort(function (Item $a, Item $b) {
if ($a->source == 'A') {
if ($b->source == 'M' || ($b->source == 'A' && $a->price < $b->price)) {
return -1;
} elseif ($b->source == 'A' && $a->price == $b->price) {
return 0;
} else {
return 1;
}
} else {
if ($b->source == 'A' || ($b->source == 'M' && $b->price < $a->price)) {
return 1;
} elseif ($b->source == 'M' && $b->price == $a->price) {
return 0;
} else {
return -1;
}
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.