data = [{id: 1, total: 400},{id: 2, total: 100},{id: 3, total: 500},{id: 4, total: 10}]
如何按总数对该数组排序?另外,我尝试使字段总数总计,但失败了.
foreach($data as $val){
$d[] = $val['total'];
}
return $d;
并得到了这个错误.
Cannot use object of type stdClass as array
解决方法:
尝试使用usort:如果您仍使用PHP 5.2或更早版本,则必须首先定义一个排序函数:
$json = '[{"id": 1, "total": 400}, {"id": 2, "total": 100}, {"id": 3, "total": 500}, {"id": 4, "total": 10}]';
$myArray = json_decode($json, true);
function sortByOrder($a, $b)
{
return $a['total'] - $b['total'];
}
usort($myArray, 'sortByOrder');
print_r($myArray);
从PHP 5.3开始,您可以使用匿名函数:
usort($myArray, function ($a, $b) {
return $a['total'] - $b['total'];
});
最后,在PHP 7中,您可以使用“太空飞船操作符”:
usort($myArray, function ($a, $b) {
return $a['type'] <=> $b['type'];
});
输出:
Array
(
[0] => Array
(
[id] => 4
[total] => 10
)
[1] => Array
(
[id] => 2
[total] => 100
)
[2] => Array
(
[id] => 1
[total] => 400
)
[3] => Array
(
[id] => 3
[total] => 500
)
)