Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php sort mutidimensional array by column name

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

like image 404
Kerwin Avatar asked Dec 07 '25 06:12

Kerwin


1 Answers

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
        )

)
like image 126
Chetan Ameta Avatar answered Dec 09 '25 20:12

Chetan Ameta