-2

可能重复:
根据数组的值对数组进行排序

我想按其中的值对数组进行排序。我试过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。

当然,我也希望保留子数组。

谢谢!

4

2 回答 2

2

文档: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');
于 2012-10-25T16:12:44.820 回答
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
                        )

                )

        )

)
于 2012-10-25T16:20:40.703 回答