PHP按数值排序数组

时间:2016-04-20 11:23:24

标签: php arrays sorting

让我们看一下打印出来的数组:

Array
(
    [0] => B
    [1] => E
    [2] => A
    [3] => D 4
    [4] => D 3
    [5] => D 2
    [6] => D
    [7] => C
    [8] => G
    [9] => F
)

有没有办法让它看起来像这样:

Array
    (
        [0] => B
        [1] => E
        [2] => A
        [3] => D 
        [4] => D 2
        [5] => D 3
        [6] => D 4
        [7] => C
        [8] => G
        [9] => F
    )

所以只对数值进行排序。 我试过sort($array); 但这按字母顺序排序

任何人都可以帮助我吗?

提前致谢!

3 个答案:

答案 0 :(得分:0)

$a = array('B', 'E', 'A', 'D 4', 'D 3', 'D 2', 'D', 'C', 'G', 'F');
natsort($a);
print_r($a);

结果

Array
(
    [2] => A
    [0] => B
    [7] => C
    [6] => D
    [5] => D 2
    [4] => D 3
    [3] => D 4
    [1] => E
    [9] => F
    [8] => G
)

more details

答案 1 :(得分:0)

<?php 
    $numbers= array("0"=>b,"1"=>e,"2"=>a,"3"=>d4,"4"=>d3,"5"=>d2,"6"=>d3,"7"=>c,"8"=>g,"9"=>f); 
    sort($numbers);
    foreach($numbersas $x => $x_value) {
       echo "Key=" . $x . ", Value=" . $x_value;
       echo "<br>";
    }
?>

尝试使用krsort()

答案 2 :(得分:0)

这是我提出的解决方案:

<?php

$array = array('B', 'E', 'A', 'D 4', 'D 3', 'D 2', 'D', 'C', 'G', 'F');


$map = [];
foreach($array as $token)
{
        $split = explode(' ', $token);

        if( !isset($map[$split[0]]) )
        {
                $map[$split[0]] = []; // initialize letter bucket
        }

        if(count($split) < 2)
        {
                $map[$split[0]][] = 0;
        }
        else
        {
                $map[$split[0]][] = intval($split[1]);
        }
}

$finalArray = [];
foreach($map as $key => $value)
{
        sort($value);
        foreach($value as $num)
        {
                if($num === 0) $finalArray[] = $key;
                else $finalArray[] = $key . ' ' .$num;
        }
}

var_dump($finalArray);

?>

输出

[root@local]# php test.php
array(10) {
  [0]=>
  string(1) "B"
  [1]=>
  string(1) "E"
  [2]=>
  string(1) "A"
  [3]=>
  string(1) "D"
  [4]=>
  string(3) "D 2"
  [5]=>
  string(3) "D 3"
  [6]=>
  string(3) "D 4"
  [7]=>
  string(1) "C"
  [8]=>
  string(1) "G"
  [9]=>
  string(1) "F"
}