PHP按升序排序Varchar数据数组

时间:2015-06-21 17:43:26

标签: php arrays sorting cakephp-2.3

我想通过PHP代码按升序对varchar数据数组进行排序 我试过这样做,我得到的结果是:

ABC1
ABC10
ABC11
ABC11A
ABC11B
ABC2
ABC2A
ABC20
ABC3

但我想:

ABC1
ABC2
ABC2A
ABC3
ABC10
ABC11
ABC11A
ABC11B
ABC20

有没有办法实现这个目标?

1 个答案:

答案 0 :(得分:1)

$myarray= array("ABC1","ABC10","ABC11","ABC11A","ABC11B","ABC2","ABC2A","ABC20","ABC3");

 natsort($myarray);
 var_dump($myarray);

结果

array(9) {
  [0]=>
  string(4) "ABC1"
  [5]=>
  string(4) "ABC2"
  [6]=>
  string(5) "ABC2A"
  [8]=>
  string(4) "ABC3"
  [1]=>
  string(5) "ABC10"
  [2]=>
  string(5) "ABC11"
  [3]=>
  string(6) "ABC11A"
  [4]=>
  string(6) "ABC11B"
  [7]=>
  string(5) "ABC20"
}
由于在评论中讨论了

更新

$keys = array_keys($myarray);
natsort($keys);
$newarray = array();
foreach ($keys as $k) $newarray[] = $myarray[$k];