Ninja
Ninja

Reputation: 5152

Array key is lost upon multidimensional associaltive array sort

This is the array that I have :

Array
            (
                [02nd Apr-04th Apr] => Array
                    (
                        [facebook] => 0
                        [youtube] => 9
                        [timestamp] => 1491177600
                    )

                [03rd Mar-05th Mar] => Array
                    (
                        [facebook] => 0
                        [youtube] => 0
                        [timestamp] => 1488672000
                    )

)

I want to sort this by "timestamp" value. So the expected output is:

Array
            (
                [03rd Mar-05th Mar] => Array
                    (
                        [facebook] => 0
                        [youtube] => 0
                        [timestamp] => 1488672000
                    )
                [02nd Apr-04th Apr] => Array
                    (
                        [facebook] => 0
                        [youtube] => 9
                        [timestamp] => 1491177600
                    )

)

What I did :

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

When I did this, the sorting worked but the array keys were lost. This is the result I got :

Array
            (
                [0] => Array
                    (
                        [facebook] => 0
                        [youtube] => 0
                        [timestamp] => 1488672000
                    )
                [1] => Array
                    (
                        [facebook] => 0
                        [youtube] => 9
                        [timestamp] => 1491177600
                    )

)

Upvotes: 0

Views: 50

Answers (2)

LF-DevJourney
LF-DevJourney

Reputation: 28559

usort cannot keep the key, use uasort to replace it. And you can use <=> to simplify you compare function.

uasort($array, function($a, $b) {
   return ($a['timestamp'] <=> $b['timestamp']);
})

Upvotes: 0

Ralph John Galindo
Ralph John Galindo

Reputation: 1190

Use uasort :

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

Upvotes: 2

Related Questions