Reputation: 339
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
Upvotes: 3
Views: 1700
Reputation: 7896
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
)
)
Upvotes: 2
Reputation: 4513
Required: Sort the array of objects by the total
property.
$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
)
)
Upvotes: 1