根据键和值的多个条件进行排序

编程入门 行业动态 更新时间:2024-10-11 21:20:18
本文介绍了根据键和值的多个条件进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想使用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] => 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] => 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.

更多推荐

根据键和值的多个条件进行排序

本文发布于:2023-10-31 09:43:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545756.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   条件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!