如何按照其中的特定值对数组进行排序?

时间:2012-10-25 16:08:55

标签: php arrays sorting

  

可能重复:
  Sorting an array based on its value

我想通过其中的值对数组进行排序。我尝试了usort但是它实际上改变了输出的值而不是仅仅移动数组中的元素会导致一些意想不到的结果。

下面是我要排序的数组:

Array
(
[element1] => Array
    (
        [Total] => 1
        [paTotal] => 0
        [totalPreregistrations] => 7
        [totalPreregistrationsToDate] => 26
        [pas] => Array
            (
                [0] => Array
                    (
                        [id] => 119
                    )

            )

    )

[element2] => Array
    (
        [Total] => 1
        [paTotal] => 0
        [totalPreregistrations] => 0
        [totalPreregistrationsToDate] => 58
        [pas] => Array
            (
                [0] => Array
                    (
                        [id] => 107
                    )

            )

    )
... element3, 4, etc...

我想按“totalPreregistrations”编号进行排序,以便如果element2的totalPreregistrations计数超过element1,则element2会超过element1。

当然我也希望保留子阵列。

谢谢!

2 个答案:

答案 0 :(得分:2)

Documentation: uasort()

function mySort($a, $b) {
  if( $a['totalPreregistrations'] == $b['totalPreregistrations'] ) {
    return 0;
  } else if( $a['totalPreregistrations'] > $b['totalPreregistrations'] ) {
    return 1;
  } else {
    return -1;
  }
}

uasort($array, 'mySort');

答案 1 :(得分:1)

您可以使用uasort代替usort

uasort($array, function ($a, $b) {
    $a = $a['totalPreregistrations'];
    $b = $b['totalPreregistrations'];
    return ($a == $b) ? 0 : (($a < $b) ? -1 : 1);
});


echo "<pre>";
print_r($array);

输出

Array
(
    [element2] => Array <-------------------------- element key remains intact 
        (
            [Total] => 1
            [paTotal] => 0
            [totalPreregistrations] => 0
            [totalPreregistrationsToDate] => 58
            [pas] => Array
                (
                    [0] => Array
                        (
                            [id] => 107
                        )

                )

        )

    [element1] => Array
        (
            [Total] => 1
            [paTotal] => 0
            [totalPreregistrations] => 7
            [totalPreregistrationsToDate] => 26
            [pas] => Array
                (
                    [0] => Array
                        (
                            [id] => 119
                        )

                )

        )

)