data = [{id: 1, total: 400},{id: 2, total: 100},{id: 3, total: 500},{id: 4, total: 10}]
How can I sort that array by total? Also I've tried to get the field total but I failed.
foreach($data as $val){
$d[] = $val['total'];
}
return $d;
And got this error.
Cannot use object of type stdClass as array
Try a usort: If you are still on PHP 5.2 or earlier, you'll have to define a sorting function first:
$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);
Starting in PHP 5.3, you can use an anonymous function:
usort($myArray, function ($a, $b) {
return $a['total'] - $b['total'];
});
And finally with PHP 7 you can use the "spaceship operator":
usort($myArray, function ($a, $b) {
return $a['type'] <=> $b['type'];
});
Output:
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
)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With