我正在按price
对以下数组进行排序。
<?php
$products = [
[
'state' => 'stocked',
'price' => 1.00,
],
[
'state' => 'out-of-stock',
'price' => 1.50,
],
[
'state' => 'unknown',
'price' => 1.25
],
[
'state' => 'stocked',
'price' => 1.75
]
];
usort($products, function($a, $b) {
return $a['price'] <=> $b['price']; // sort by price ASC
});
var_dump($products);
结果按预期工作正常:
array(4) {
[0]=>
array(2) {
["state"]=>
string(7) "stocked"
["price"]=>
float(1)
}
[1]=>
array(2) {
["state"]=>
string(7) "unknown"
["price"]=>
float(1.25)
}
[2]=>
array(2) {
["state"]=>
string(12) "out-of-stock"
["price"]=>
float(1.5)
}
[3]=>
array(2) {
["state"]=>
string(7) "stocked"
["price"]=>
float(1.75)
}
}
但是,我需要优先选择一个州(例如stocked
),不要按其他州排序,并且然后按州集合内的价格排序。
所以我想要的输出是:
array(4) {
[1]=> // "stocked" first, then sort by price
array(2) {
["state"]=>
string(7) "stocked"
["price"]=>
float(1)
}
[2]=> // "stocked" first, then sort by price
array(2) {
["state"]=>
string(7) "stocked"
["price"]=>
float(1.75)
}
[3]=> // any other state, then sort by price
array(2) {
["state"]=>
string(7) "unknown"
["price"]=>
float(1.25)
}
[3]=> // any other state, then sort by price
array(2) {
["state"]=>
string(12) "out-of-stock"
["price"]=>
float(1.5)
}
}
我能够找到这组代码片段(link),以按多个属性进行排序,但是它们没有考虑任何首选值,所以我有点迷失了。
任何帮助将不胜感激。
经过一番尝试和错误之后,我能够编写正确的排序算法:
usort($products, function($a, $b) {
if ($a['state'] === 'stocked') {
return -1;
} elseif ($b['state'] === 'stocked') {
return 1;
}
return $a['price'] <=> $b['price'];
});