本文介绍了我怎么然后通过PHP的价值排序字符串长度的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
目前,我有我的数组通过字符串长度排序。但是,当字符串长度相等,我怎么排序的价值?
作为一个例子,我现在的code:
$阵列=阵列(A,BC,AA,C,BB,B);功能lensort($ A,$ B){
返回的strlen($ A)-strlen($ B);
}usort($阵列,'lensort');的print_r($数组);
输出:
阵列
(
[0] => C
[1] =>一个
[2] =>乙
[3] => BB
[4] => AA
[5] =>公元前
)
不过,我想它由以下代替排序:
阵列
(
[0] =>一个
[1] =>乙
[2] => C
[3] => AA
[4] => BB
[5] =>公元前
)
解决方案
二者结合检查到你的比较:
函数lensort($ A,$ B){
$ LA = strlen的($ A); $磅= strlen的($ B);
如果($ LA == $磅){
返回STRCMP($ A,$ B);
}
回拉$ - $磅;
}
您可以从,这将显示:
阵列
(
[0] =>一个
[1] =>乙
[2] => C
[3] => AA
[4] => BB
[5] =>公元前
)
Currently, I have my array sorting by string length. But, when the string lengths are equal, how do I sort by value?
As an example, my current code:
$array = array("A","BC","AA","C","BB", "B");
function lensort($a,$b){
return strlen($a)-strlen($b);
}
usort($array,'lensort');
print_r($array);
Outputs:
Array
(
[0] => C
[1] => A
[2] => B
[3] => BB
[4] => AA
[5] => BC
)
But, I'd like it to sort by the following instead:
Array
(
[0] => A
[1] => B
[2] => C
[3] => AA
[4] => BB
[5] => BC
)
解决方案
Incorporate both checks into your comparator:
function lensort($a,$b){
$la = strlen( $a); $lb = strlen( $b);
if( $la == $lb) {
return strcmp( $a, $b);
}
return $la - $lb;
}
You can see from this demo that this prints:
Array
(
[0] => A
[1] => B
[2] => C
[3] => AA
[4] => BB
[5] => BC
)
这篇关于我怎么然后通过PHP的价值排序字符串长度的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!