4

I have an associative array like this

Array
(
    ["News 1"] => Array
        (
            [text] => tests
            [language] => 
            [advertiserCompetitionScale] => 5
            [avgSearchVolume] => 7480000
            [lastMonthSearchVolume] => 9140000
        )

    ["News 2"] => Array
        (
            [text] => personality tests
            [language] => 
            [advertiserCompetitionScale] => 5
            [avgSearchVolume] => 165000
            [lastMonthSearchVolume] => 201000
        )

    ["News 3] => Array
        (
            [text] => online tests
            [language] => 
            [advertiserCompetitionScale] => 5
            [avgSearchVolume] => 246000
            [lastMonthSearchVolume] => 301000
        )

)

I managed to sort it by the column i want (LastMonthSearchVolume for example)

// compare function 
function cmpi($a, $b) 
{ 

     return strcmp($a["lastMonthSearchVolume"], $b["lastMonthSearchVolume"]); 
} 

// do the array sorting 
usort($latest_array, 'cmpi');

The problem is when i dump the array to see the result the usort broke my associative array by removing "News 1", "News 2" etc.. and replacing it by 0,1,2...

Is there any solution to make sort keep the column name ?

Thanks

Alexis
  • 1,825
  • 4
  • 23
  • 28

2 Answers2

4

In place of usort, use the function uasort, which preserves index association.

1

Use uasort instead. usort does not maintain associative keys, while uasort does.

Xyz
  • 5,955
  • 5
  • 40
  • 58