PHP usort() 按具有首选值的多个属性
PHP usort() by multiple properties with a preferred value
我正在按 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'];
});
我正在按 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'];
});