user3657517 user3657517 - 3 months ago 6
JSON Question

Using usort to sort json output

I have below json outout. Can anyone please suggest how to sort this according to "no_count" column?

$arr= {"UserHeader":[

{"id":"154", "no_count":15},
{"id":"155", "no_count":11},
{"id":"158", "no_count":13},
{"id":"159", "no_count":31},
{"id":"164", "no_count":11}

]}


I have used USORT but no luck. The code is not working and give me the same array without sorting.

usort($arr, function($a, $b) { //Sort the array using a user defined function
return $a->no_count > $b->no_count ? -1 : 1; //Compare the scores
});

print_r($arr);


Might be a small formatting error.

Thanks

Answer

I did some corrections :

$arr = json_decode('{"UserHeader":[
{"id":"154", "no_count":15},
{"id":"155", "no_count":11},
{"id":"158", "no_count":13},
{"id":"159", "no_count":31},
{"id":"164", "no_count":11}
]}');

usort($arr->UserHeader, function ($a, $b) { //Sort the array using a user defined function
    return $a->no_count > $b->no_count ? -1 : 1; //Compare the scores
});

print_r($arr);

It should work as expected.