如何在PHP中对此数组进行排序?

时间:2015-07-17 03:28:05

标签: php arrays sorting

我一直在尝试使用sort()函数将数组从最小到最大重新排列。

这是我的print_r数组,来自被破坏的序列化数据:

Array
    (
    [0] => 127173
    [1] => 127172
    [2] => 127174
    [3] => 127175
    [4] => 127178
    [5] => 127176
    [6] => 127177
    [7] => 127179
    [8] => 127180
    [9] => 127183
    [10] => 127181
    )

使用sort()asort()我只返回1。

2 个答案:

答案 0 :(得分:2)

试试这段代码......实际上sort功能正常。

$array = Array
    (
    '0' => 127173,
    '1' => 127172,
    '2' => 127174,
    '3' => 127175,
    '4' => 127178,
    '5' => 127176,
    '6' => 127177,
    '7' => 127179,
    '8' => 127180,
    '9' => 127183,
    '10' => 127181
    );

sort($array); // <= Sort the array desc

foreach( $array as $key => $value ){
    echo $key."\t=>\t".$value."\n";
}
  

考虑sort函数实际更改您的数组并返回 bool See doc

Check this example online

答案 1 :(得分:0)

使用asort(),如下所示:

$A = Array (127173,127172,127174,127175,127178,127176,127177,127179,127180,127183,127181);
asort($A);
print_r($A);

结果:

Array ( [1] => 127172 [0] => 127173 [2] => 127174 [3] => 127175 [5] => 127176 [6] => 127177 [4] => 127178 [7] => 127179 [8] => 127180 [10] => 127181 [9] => 127183 )

在此处比较排序函数:http://php.net/manual/en/array.sorting.php