我遇到了标题中描述的问题。
我的数组需要arsort
函数(我需要从高到低并保持键)。
但是在字母字符之前我需要数字。
示例:
["5","2","1","D","BC","A"]
标准 arsort():
["D","BC","A","5","2","1"]
我需要:
["5","2","1","D","BC","A"]
我认为我必须使用其他功能,而不是使用其他功能,或者自己动手。
有人可以帮助我吗?
答案 0 :(得分:1)
正如我在评论中建议的那样,如果你的键不要将数字和字母字符混合在一起,你可以转换数字键,缩短数组,然后将其转换回来:
<?php
$array = ["5","2","1","D","BC","A"];
$array2 = [];
foreach($array as $value) {
if(is_numeric ($value)){
$array2[] = intval($value);
} else {
$array2[] = $value;
}
}
arsort($array2);
$endArray = [];
foreach($array2 as $value) {
if(is_int($value)){
$endArray[] = "$value";
} else {
$endArray[] = $value;
}
}
var_dump($endArray);
答案 1 :(得分:1)
$array = array("3", "1", "10","5","A","B","Z","C");
sort($array, SORT_NATURAL);
var_dump($array);
array(8) {
[0]=>
string(1) "1"
[1]=>
string(1) "3"
[2]=>
string(1) "5"
[3]=>
string(2) "10"
[4]=>
string(1) "A"
[5]=>
string(1) "B"
[6]=>
string(1) "C"
[7]=>
string(1) "Z"
}
按保留键的值(降序)自然排序:
$array = array("10"=>"3", "a"=>"1", 2=>"10","3"=>"5", "1"=>"A","20"=>"B","5"=>"Z","123"=>"C");
natsort($array);
$array = array_reverse($array, true);
var_dump($array);
array(8) {
[0]=>
string(1) "Z"
[1]=>
string(1) "C"
[2]=>
string(1) "B"
[3]=>
string(1) "A"
[4]=>
string(2) "10"
[5]=>
string(1) "5"
[6]=>
string(1) "3"
["a"]=>
string(1) "1"
}
它应该有效,除非你想要一个不同的排序标准,那么你应该更好地解释它。
$array = array(6=>"115-0001 LMH", 7=>"158-0154 FGM", 8=>"116-0115 Korea", 9=>"VG1305154454", 0=>"VGE54815313", "10"=>"3", "a"=>"1", 2=>"10","3"=>"5", "1"=>"A","20"=>"B","5"=>"Z","123"=>"C");
natsort($array);
$array = array_reverse($array, true);
var_dump($array);
array(13) {
[5]=>
string(1) "Z"
[0]=>
string(11) "VGE54815313"
[9]=>
string(12) "VG1305154454"
[123]=>
string(1) "C"
[20]=>
string(1) "B"
[1]=>
string(1) "A"
[7]=>
string(12) "158-0154 FGM"
[8]=>
string(14) "116-0115 Korea"
[6]=>
string(12) "115-0001 LMH"
[2]=>
string(2) "10"
[3]=>
string(1) "5"
[10]=>
string(1) "3"
["a"]=>
string(1) "1"
}
答案 2 :(得分:-1)
很抱歉第一次回答错误,现在 *已更新*
<?php
$arr = ["1","2","5","D","A","BC"];
$nums = [];
$chars = [];
foreach($arr as $v){
if(is_numeric($v)){
$nums[] = $v;
}else{
$chars[] = $v;
}
}
rsort($nums);
arsort($chars);
$output = array_merge($nums, $chars);
print_r($output);
?>
中试用