PHP:排序其值的长度数组? [英] PHP: Sort an array by the length of its values?

查看:83
本文介绍了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?

推荐答案

使用<一个href=\"http://us2.php.net/manual/en/function.usort.php\">http://us2.php.net/manual/en/function.usort.php

这个自定义函数

function sort($a,$b){
    return strlen($b)-strlen($a);
}

usort($array,'sort');

如果你想保留旧的索引,使用usort如果你不小心使用uasort。

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屋!

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