PHP多维数组(usort)

时间:2012-02-28 13:56:42

标签: php arrays sorting associative usort

我有像这样的关联数组

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
        )

)

我设法按照我想要的列(例如LastMonthSearchVolume)对其进行排序

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

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

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

问题是当我转储数组以查看结果时,usort通过删除“新闻1”,“新闻2”等来破坏我的关联数组。并将其替换为0,1,2 ......

是否有任何解决方案可以使列保持列名?

由于

2 个答案:

答案 0 :(得分:4)

使用保留索引关联的函数usort代替uasort

答案 1 :(得分:1)

请改用uasortusort不会维护关联键,uasort会这样做。