PHP:按其值的长度对数组进行排序? [英] PHP: Sort an array by the length of its values?
本文介绍了PHP:按其值的长度对数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我制作了一个字谜机器,我有一系列正匹配.问题是它们的顺序不同,我希望能够对数组进行排序,以便最长的数组值首先出现.
I made an anagram machine and I have an array of positive matches. The trouble is they are all in a different order, I want to be able to sort the array so the longest array values appear first.
有人对如何做到这一点有任何想法吗?
Anybody have any ideas on how to do this?
推荐答案
使用 http://us2.php.net/manual/en/function.usort.php
使用这个自定义函数
function sort($a,$b){
return strlen($b)-strlen($a);
}
usort($array,'sort');
如果您想保留旧索引,请使用 uasort,如果您不关心,请使用 usort.
Use uasort if you want to keep the old indexes, use usort if you don't care.
另外,我相信我的版本更好,因为 usort 是一种不稳定的排序.
Also, I believe that my version is better because usort is an unstable sort.
$array = array("bbbbb", "dog", "cat", "aaa", "aaaa");
// mine
[0] => bbbbb
[1] => aaaa
[2] => aaa
[3] => cat
[4] => dog
// others
[0] => bbbbb
[1] => aaaa
[2] => dog
[3] => aaa
[4] => cat
这篇关于PHP:按其值的长度对数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文