chr*_*ris 13 php arrays sorting
我有一个阵列..
$test = array("def", "yz", "abc", "jkl", "123", "789", "stu");
Run Code Online (Sandbox Code Playgroud)
如果我sort()坚持下去,我得到
Array
(
[0] => 123
[1] => 789
[2] => abc
[3] => def
[4] => jkl
[5] => stu
[6] => yz
)
Run Code Online (Sandbox Code Playgroud)
但我想看到它
Array
(
[0] => abc
[1] => def
[2] => jkl
[3] => stu
[4] => yz
[5] => 123
[6] => 789
)
Run Code Online (Sandbox Code Playgroud)
我试过array_reverse,似乎没有改变任何东西.所以我现在迷失了如何获得最后的数字,但也是如此
Div*_*com 13
你需要的是排序,但有自定义比较功能(usort).以下代码将完成它:
function myComparison($a, $b){
if(is_numeric($a) && !is_numeric($b))
return 1;
else if(!is_numeric($a) && is_numeric($b))
return -1;
else
return ($a < $b) ? -1 : 1;
}
$test = array("def", "yz", "abc", "jkl", "123", "789", "stu");
usort ( $test , 'myComparison' );
Run Code Online (Sandbox Code Playgroud)
您可以在排序之前将数字转换为整数:
$array = array("def", "yz", "abc", "jkl", "123", "789", "stu");
foreach ($array as $key => $value) {
if (ctype_digit($value)) {
$array[$key] = intval($value);
}
}
sort($array);
print_r($array);
Run Code Online (Sandbox Code Playgroud)
输出:
Array
(
[0] => abc
[1] => def
[2] => jkl
[3] => stu
[4] => yz
[5] => 123
[6] => 789
)
Run Code Online (Sandbox Code Playgroud)