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;
得到了这个错误。
不能使用stdClass类型的对象作为数组
答案 0 :(得分:2)
尝试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
)
)
答案 1 :(得分:1)
必需:按total
属性对对象数组进行排序。
$json = '[{"id": 1, "total": 400}, {"id": 2, "total": 100}, {"id": 3, "total": 500}, {"id": 4, "total": 10}]';
$data = json_decode($json);
usort($data, function ($t1, $t2) {
return $t1->total - $t2->total;
});
echo '<pre>';
print_r($data);
echo '</pre>';
Array
(
[0] => stdClass Object
(
[id] => 4
[total] => 10
)
[1] => stdClass Object
(
[id] => 2
[total] => 100
)
[2] => stdClass Object
(
[id] => 1
[total] => 400
)
[3] => stdClass Object
(
[id] => 3
[total] => 500
)
)