我制作了一个字谜机器,我有一系列正匹配.问题是它们的顺序不同,我希望能够对数组进行排序,以便最长的数组值首先出现.
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?
推荐答案使用 us2.php/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