此问题旨在作为有关在PHP中排序数组的问题的参考.很容易认为您的特定情况是独一无二的,值得一个新问题,但大多数实际上是本页面上其中一个解决方案的微小变化.
如果您的问题与此问题的副本相同,请仅在您能够解释为何与以下所有问题明显不同时才要求重新打开您的问题.
如何在PHP中对数组进行排序?
如何在PHP中对复杂数组进行排序?
如何在PHP中对对象数组进行排序?
有关使用PHP现有函数的实际答案,请参阅1.,有关排序算法的学术详细答案(PHP的函数实现以及您可能需要哪些非常复杂的案例),请参阅参考资料2.
array(10) {
[1019]=> array(3) { ["quantity"]=> int(0) ["revenue"]=> int(0) ["seller"]=> string(5) "Lenny" }
[1018]=> array(3) { ["quantity"]=> int(5) ["revenue"]=> int(121) ["seller"]=> string(5) "Lenny" }
[1017]=> array(3) { ["quantity"]=> int(2) ["revenue"]=> int(400) ["seller"]=> string(6) "Anette" }
[1016]=> array(3) { ["quantity"]=> int(25) ["revenue"]=> int(200) ["seller"]=> string(6) "Samuel" }
[1015]=> array(3) { ["quantity"]=> int(1) ["revenue"]=> int(300) ["seller"]=> string(6) "Samuel" }
[1014]=> array(3) { ["quantity"]=> string(2) "41" ["revenue"]=> string(5) "18409" ["seller"]=> string(6) "Samuel" }
}
Run Code Online (Sandbox Code Playgroud)
我正在使用上面的数组.调用这个多维数组$stats.
我想按数量对这个数组进行排序.
因此,multidim阵列具有其第一阵列1016,然后是1018,1017等等.
我这样做是通过:
function compare($x, $y) …Run Code Online (Sandbox Code Playgroud) 如何对多维数组进行深度排序并保留其键?
$array = [
'2' => [
'title' => 'Flower',
'order' => 3
],
'3' => [
'title' => 'Rock',
'order' => 1
],
'4' => [
'title' => 'Grass',
'order' => 2
]
];
foreach ($array as $key => $row) {
$items[$key] = $row['order'];
}
array_multisort($items, SORT_DESC, $array);
print_r($array);
Run Code Online (Sandbox Code Playgroud)
结果:
Array
(
[0] => Array
(
[title] => Flower
[order] => 3
)
[1] => Array
(
[title] => Grass
[order] => 2
)
[2] => Array
(
[title] …Run Code Online (Sandbox Code Playgroud)