PHP多维数组(usort)

标签 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 通过删除“News 1”、“News 2”等破坏了我的关联数组,并将其替换为 0,1,2...

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

谢谢

最佳答案

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

关于PHP多维数组(usort),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9483215/

相关文章:

algorithm - 在数组中查找重复项的最快方法

php - 使用 PHP 将 HTML 表单中的数据插入到 MySQL 数据库

php - 用于匹配(并删除)包含文件中的多行 PHP 代码的正则表达式模式

arrays - 在 Ruby 中合并两个对象数组

java - 检查数组是否对称

php - PHP 中 natsort 的任何替代方案,在处理带零的字母数字字符时不会失败

php - 在 laravel 5.2 中使用 Redis 作为队列驱动程序时是否需要创建失败的作业表?

php - checkout.php 没有从managecart.php 获取值(value)

php - array_push 创建新数组而不是添加

python - 如何按字母顺序对大型文本文件进行排序?