PHP multidimensional array (usort)

时光毁灭记忆、已成空白 提交于 2019-12-10 16:18:33

问题


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


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/9483215/php-multidimensional-array-usort

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!