Array sorting by key value in php
我想根据数量在数组下面排序,但不知道如何排序。有人帮帮我
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| Array(
[0] => Array
(
[id ] => 1
[amount ] => 20
)
[1] => Array
(
[id ] => 2
[amount ] => 30
)
[2] => Array
(
[id ] => 3
[amount ] => 10
)
) |
- usortnet /手动/恩/ function.usort.php如果你使用,你可以使用php7操作员是新这里!<=>
- 可能重复的多维数组sort of red价值
之类的东西
php7 +
1 2 3
| usort($array, function($a, $b){
return $a['amount'] <=> $b['amount'];
}); |
什么是< = >("spaceship"operator)在PHP 7?
PHP<7
1 2 3 4 5 6 7 8
| usort($array, function($a, $b){
if( $a['amount'] == $b['amount'] )
return 0;
else if($a['amount'] > $b['amount'])
return 1;
else
return -1
}); |
或你只是像其他人subtract……
usort[ 1 ]将做的工作采用自定义功能指标为对照,在amount性质和一个标准的比较performs为整数为大于/小于。黑与descending $b["amount"] - $a["amount"]如果你的愿望。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| $data = [
[
"id" => 1,
"amount" => 20
],
[
"id" => 2,
"amount" => 30,
],
[
"id" => 3,
"amount" => 10
]
];
usort($data, function ($a, $b) {
return $a["amount"] - $b["amount"];
});
print_r($data); |
输出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| Array
(
[0] => Array
(
[id ] => 3
[amount ] => 10
)
[1] => Array
(
[id ] => 1
[amount ] => 20
)
[2] => Array
(
[id ] => 2
[amount ] => 30
)
) |
这里的复制与测试。
使用usort。
e.g
1 2 3 4 5 6
| function sortByAmount ($x, $y) {
return $x['amount'] - $y['amount'];
}
usort($array, 'sortByAmount');
echo"[cc lang="php "]"; print_r($array); |
- 你应该考虑的问题sridharg @ artisticphoenix as from the right as辐射问题问题你solved as the first one。