PHP 数组多重排序 - 按值然后按键? [英] PHP array multiple sort - by value then by key?

查看:30
本文介绍了PHP 数组多重排序 - 按值然后按键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有数值的字符串键数组,用于带有每个标签出现次数的标签列表,因此:

I have an array of string keys with numeric values for use in a list of tags with the number of occurances of each tag, thus:

$arrTags['mango'] = 2; 
$arrTags['orange'] = 4; 
$arrTags['apple'] = 2; 
$arrTags['banana'] = 3;

这样我就可以按降序显示标签列表:

this is so i can display the tag list in descending occurance order thus:

orange (4)  
banana (3) 
mango (2) 
apple (2)

我可以使用 arsort 按值进行反向排序,这很好,但我也希望任何具有相同数值的标签按字母顺序排序,因此最终结果可以是:

i can use arsort to reverse sort by the value which is brilliant but i also want any tags that have the same numeric value to be sorted alphabetically, so the final result can be:

orange (4)  
banana (3) 
apple (2) 
mango (2)

有没有办法做到这一点?我猜 usort 可能是要走的路,但我看着 php.net 上的例子,我的眼睛呆滞了!非常感谢!!!

is there a way i can do this? i'm guessing that usort may be the way to go but i look at the examples on php.net and my eyes glaze over! many thanks!!!

推荐答案

看看示例 #3:http://php.net/manual/en/function.array-multisort.php

您需要创建两个数组作为索引;一个由原始数组的键和另一个原始数组的值组成.

You'll need to create two arrays to use as indexes; one made up of the original array's keys and the other of the original array's values.

然后使用 multisort 按文本值(原始数组的键)和数值(原始数组的值)排序.

Then use multisort to sort by text values (keys of the original array) and then by the numeric values (values of the original array).

这篇关于PHP 数组多重排序 - 按值然后按键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆