data = [{id: 1, total: 400},{id: 2, total: 100},{id: 3, total: 500},{id: 4, total: 10}]
我该如何按总数对数组进行排序?我尝试获取total字段,但失败了。
foreach($data as $val){
$d[] = $val['total'];
}
return $d;
我遇到了这个错误。
无法将stdClass对象用作数组
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对象用作数组
尝试使用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
)
)
需要:按 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
)
)
json_encode($phpDataItem);
,其中dataItem
是一个PHP数组等。 - Ryan Vincent$val
保存了你想要排序的数组。如果你使用var_dump($val);
,你应该能看到如何对其进行排序。或者,根据你已经创建的查询,它们可以通过使用“union”和“group by”的“sum”进行组合。同时应用“order by”,它应该会返回你想要的数组。 - Ryan Vincent