0

I need to sort an array like this

     [0] => Array
            (
                [id] => 5
                [stats] => Array
                    (
                        [SessionsPlayed] => 1
                    )

            )
     [1] => Array
            (
                [id] => 88
                [stats] => Array
                    (
                        [SessionsPlayed] => 6
                    )

            )
     [2] => Array
            (
                [id] => 22
                [stats] => Array
                    (
                        [SessionsPlayed] => 9
                    )

            )

So that it is in descending order by the SessionPlayed column like this.

     [2] => Array
            (
                [id] => 22
                [stats] => Array
                    (
                        [SessionsPlayed] => 9
                    )

            )
     [1] => Array
            (
                [id] => 88
                [stats] => Array
                    (
                        [SessionsPlayed] => 6
                    )

            )
     [0] => Array
            (
                [id] => 5
                [stats] => Array
                    (
                        [SessionsPlayed] => 1
                    )

            )

I have attempted to look online on how to solve this but all of the answer I find can only sort down one child ( ex. the id column ) Here are the posts I looked at. https://stackoverflow.com/a/16788610/1319033 https://stackoverflow.com/a/2699110/1319033

Community
  • 1
  • 1
Harry
  • 725
  • 3
  • 7
  • 19
  • possible duplicate of [Reference: all basic ways to sort arrays and data in PHP](http://stackoverflow.com/questions/17364127/reference-all-basic-ways-to-sort-arrays-and-data-in-php) – Sverri M. Olsen Jun 04 '14 at 17:46

1 Answers1

3

Use PHP's usort

usort($array, function($a, $b) {
    return $b['stats']['SessionsPlayed'] - $a['stats']['SessionsPlayed'];
    // $b - $a for descending order
});
Felk
  • 7,720
  • 2
  • 35
  • 65
  • 1
    The way I showed here. `usort` sorts an array and uses an user-defines comparing function – Felk Jun 04 '14 at 17:23