-2

Possible Duplicate:
Sorting an array based on its value

I want to sort an array by a value inside of it. I tried usort but it leads to some unexpected results in actually changing the value of the output instead of just shifting elements in the array.

Below is the array I want to sort:

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...

I want to sort by the "totalPreregistrations" number so that element2 goes above element1 if element2's totalPreregistrations count goes above element1's.

And of course I want the sub-arrays to be retained as well.

Thank you!

Community
  • 1
  • 1

2 Answers2

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');
Sammitch
  • 25,490
  • 6
  • 42
  • 70
1

You can use uasort instead of 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);

Output

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
                        )

                )

        )

)
Baba
  • 89,415
  • 27
  • 158
  • 212