此问题旨在作为有关在PHP中排序数组的问题的参考.很容易认为您的特定情况是独一无二的,值得一个新问题,但大多数实际上是本页面上其中一个解决方案的微小变化.
如果您的问题与此问题的副本相同,请仅在您能够解释为何与以下所有问题明显不同时才要求重新打开您的问题.
如何在PHP中对数组进行排序?
如何在PHP中对复杂数组进行排序?
如何在PHP中对对象数组进行排序?
有关使用PHP现有函数的实际答案,请参阅1.,有关排序算法的学术详细答案(PHP的函数实现以及您可能需要哪些非常复杂的案例),请参阅参考资料2.
我正在尝试根据特定的密钥对我的PHP哈希表进行排序.数据结构如下所示:
print_r($mydata);
Array(
[0] => Array
(
[type] => suite
[name] => A-Name
)
[1] => Array
(
[type] => suite
[name] => C-Name
)
[2] => Array
(
[type] => suite
[name] => B-Name
)
)
Run Code Online (Sandbox Code Playgroud)
我尝试过ksort,sort,usort但似乎没什么用.我正在尝试根据名称键排序两级下来.
这是我尝试使用usort:
function cmp($a, $b) {
return $b['name'] - $a['name'];
}
usort($mydata, "cmp");
Run Code Online (Sandbox Code Playgroud)
有没有一种简单的方法可以做到这一点,还是我需要编写自定义排序功能?
是否有更紧凑的方法来使用 PHP \xe2\x89\xa5 7.0按两个参数/字段对数组进行排序(使用spaceship 运算符) <=>
?
现在我要排序的技巧是首先按第二个参数,然后按第一个参数:
\n// Sort by second parameter title\nusort($products, function ($a, $b) {\n return $a[\'title\'] <=> $b[\'title\']; // string\n});\n\n// Sort by first parameter brand_order\nusort($products, function ($a, $b) {\n return $a[\'brand_order\'] <=> $b[\'brand_order\']; // numeric\n});\n
Run Code Online (Sandbox Code Playgroud)\n这给了我我想要的结果;产品首先按品牌排序,然后按名称排序。
\n我只是想知道是否有办法做到这一点usort
。
这是我的问题作为代码片段。这个例子可以在这里测试。
\n<pre><?php\n \n<!-- Example array -->\n$products = array();\n\n$products[] = array("title" => "Title A", \n "brand_name" => "Brand B",\n "brand_order" => 1);\n$products[] = …
Run Code Online (Sandbox Code Playgroud)usort($childs, function($a, $b) {
return $a['parent_id'] - $b['parent_id'];
});
Run Code Online (Sandbox Code Playgroud)
在这里,我用1个字段对它进行排序,如何添加更多字段来对它们进行排序?,就好像它是ORDER BY field1, field2, field3
在Mysql中一样