如何对PHP数组进行排序,将值作为由' - '拆分的字符串

时间:2018-05-08 13:40:46

标签: php sorting

我有以下数组:

save()

我想要的是按array ( 0 => '4-0', 1 => '4-1', 2 => '4-2', 3 => '4-3', 4 => '4-4', 5 => '4-5', 6 => '4-6', 7 => '4-7', 8 => '4-8', 9 => '4-9', 10 => '4-10', 11 => '4-11', 12 => '4-12', 13 => '4-13', 14 => '4-14', 15 => '4-15', 16 => '4-16', 17 => '8-0', 18 => '9-0', 19 => '2-0', 20 => '5-0', 21 => '7-1', ) 订购ASC。所以array [19]的值应该是第一个,而数组[18]的值应该是最后一个。我尝试了一些排序功能,例如value,但它没有做我想要的。

asort()

asort()

是否有特定的PHP函数或我应该实现自己的算法?有什么想法吗?

3 个答案:

答案 0 :(得分:2)

您可以将sort()SORT_NATURAL标志一起使用:

<?php
$array = array (
  0 => '4-0',
  1 => '4-1',
  2 => '4-2',
  3 => '4-3',
  4 => '4-4',
  5 => '4-5',
  6 => '4-6',
  7 => '4-7',
  8 => '4-8',
  9 => '4-9',
  10 => '4-10',
  11 => '4-11',
  12 => '4-12',
  13 => '4-13',
  14 => '4-14',
  15 => '4-15',
  16 => '4-16',
  17 => '8-0',
  18 => '9-0',
  19 => '2-0',
  20 => '5-0',
  21 => '7-1',
);

sort( $array, SORT_NATURAL );
print_r( $array );

输出:

Array
(
    [0] => 2-0
    [1] => 4-0
    [2] => 4-1
    [3] => 4-2
    [4] => 4-3
    [5] => 4-4
    [6] => 4-5
    [7] => 4-6
    [8] => 4-7
    [9] => 4-8
    [10] => 4-9
    [11] => 4-10
    [12] => 4-11
    [13] => 4-12
    [14] => 4-13
    [15] => 4-14
    [16] => 4-15
    [17] => 4-16
    [18] => 5-0
    [19] => 7-1
    [20] => 8-0
    [21] => 9-0
)

答案 1 :(得分:0)

您可以使用natsort http://php.net/manual/en/function.natsort.php。 它会将数组内容排序为字符串。

natsort($your_array)

答案 2 :(得分:-1)

它简单,只需排序功能即可完成任务。

sort($array);

请注意,参数是按引用传递的,而不是按值传递。

<?php
$array=array (
  0 => '4-0',
  1 => '4-1',
  2 => '4-2',
  ....
  ....
);
sort($array);
print_r($array);
?>

会给出相同的答案