根据键和值的多个条件进行排序 [英] Sort based on multiple criteria on keys and values
问题描述
我想使用PHP对下面的数组进行排序.主要问题是我需要根据多个条件对数组进行排序:
I would like to sort the array below using PHP. The main problem is that I need to sort the array based on multiple criteria:
- 首先以价格显示网站
- 如果价格相同,请按字母顺序对其进行排序
- 如果多个网站没有价格,请按字母顺序对其进行排序
所以这个数组
array(
[Beslist.nl] => Array
(
[price] => 141,63
)
[Wehkamp.nl] => Array
(
[price] => none
)
[Bol.com] => Array
(
[price] => none
)
[Zalando.nl] => Array
(
[price] => none
)
[Webwinkel.nl] => Array
(
[price] => none
)
[Overig.nl] => Array
(
[price] => none
)
)
应该这样排序:
array(
[Beslist.nl] => Array
(
[price] => 141,63
)
[Bol.com] => Array
(
[price] => none
)
[Overig.nl] => Array
(
[price] => none
)
[Webwinkel.nl] => Array
(
[price] => none
)
[Wehkamp.nl] => Array
(
[price] => none
)
[Zalando.nl] => Array
(
[price] => none
)
)
我尝试了asort和ksort,但是我需要基于多个条件进行排序,这使其变得更加复杂.我希望我可以使用SQL对记录进行排序(当我从数据库中读取记录时).但是,价格需要事后计算;这就是为什么我需要使用PHP.
I tried asort and ksort, but I need to sort based on multiple criteria, which makes it more complex. I was hoping I could sort the records using SQL (when I read the records from the database). However, the price needs to be calculated afterwards; that is why I need to use PHP.
有人可以帮助我吗?
推荐答案
在此处中,有非常合适的详细方法.考虑到数组的实际结构,这可能需要更多说明.具体来说,以下是按键和值进行排序的方法:
There are perfectly suitable approaches detailed here, but considering the actual structure of your array, this probably requires a bit more explanation. Specifically, here's how you can sort by both keys and values:
uksort($array, function ($siteA, $siteB) use ($array) {
$priceA = $array[$siteA]['price'];
$priceB = $array[$siteB]['price'];
if ($priceA == $priceB) {
return strcmp($siteA, $siteB);
}
if (!$priceB) {
return -1;
}
if (!$priceA) {
return 1;
}
return $priceB - $priceA;
});
您可能需要在此处调整特定的比较并返回逻辑,但这说明了这种方法.
You might need to adjust the specific comparisons and return logic here, but this illustrates the approach.
这篇关于根据键和值的多个条件进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!