如何按照我想要的顺序对以下数据进行排序?
数组:
array(4)
{
[21]=> string(7) "2-2.pdf"
[22]=> string(7) "2-3.pdf"
[23]=> string(7) "2-4.pdf"
[24]=> string(5) "2.pdf"
}
我想要这种:
2.pdf
2-2.pdf
2-3.pdf
2-4.pdf
答案 0 :(得分:2)
是的,你可以在这种情况下使用usort:
$array = [21=> "2-2.pdf", 22=> "2-3.pdf", 23=> "2-4.pdf",24=> "2.pdf", ];
usort($array, function($a, $b){
$a = str_replace('-', '', $a);
$b = str_replace('-', '', $b);
return $a - $b;
});
答案 1 :(得分:1)
你可以这样做:
<?php
$check_array = array('2-2.pdf','2.pdf','2-3.pdf','2-4.pdf');
function cmp($a, $b)
{
$a = preg_replace('/-/','',$a);
$b = preg_replace('/-/','',$b);
return strcmp($a, $b);
}
usort($check_array, "cmp");
echo "<pre/>"; print_r($check_array);
?>
结果是:
<?php Array ( [0] => 2.pdf [1] => 2-2.pdf [2] => 2-3.pdf [3] => 2-4.pdf ) ?>