【问题标题】:PHP multidimensional array (usort)PHP多维数组(usort)
【发布时间】:2012-03-18 00:00:04
【问题描述】:

我有一个这样的关联数组

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 替换它来破坏我的关联数组...

有没有办法让 sort 保留列名?

谢谢

【问题讨论】:

    标签: php arrays sorting associative usort


    【解决方案1】:

    使用函数uasort代替usort,它保留索引关联。

    【讨论】:

      【解决方案2】:

      请改用uasortusort 不维护关联键,而 uasort 维护。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-31
        • 1970-01-01
        • 1970-01-01
        • 2019-02-08
        • 2016-07-13
        相关资源
        最近更新 更多