Sorting JSON Arrays by Value in PHP
When working with data structures returned from APIs or parsed via json_decode, you will frequently encounter arrays of objects that need reordering based on a specific metric. Consider an array where each element is a stdClass object containing properties like name, id, and a numeric score. If your goal is to sort this collection by the score value in descending order, you do not need complex custom logic; PHP provides built-in mechanisms that handle this efficiently.
The most straightforward approach for modern PHP versions (7.4+) is leveraging the usort function with a closure. This method offers fine-grained control over the sorting logic. You define a callback that accepts two argumentsâlet's call them $a and $bârepresenting the objects being compared. Inside this closure, you access the score property of both objects and calculate the difference.
Here is how you implement it:
$data = [
(object)['name' => 'Morts par Déshydratation', 'score' => 4, 'id' => 'dwater'],
(object)['name' => 'Réparations de chantiers', 'score' => 87, 'id' => 'brep'],
(object)['name' => 'Campeur téméraire', 'score' => 77, 'id' => 'camp'],
(object)['name' => 'Décoration', 'score' => 112, 'id' => 'deco'],
];
usort($data, function ($a, $b) {
if ($a->score < $b->score) {
return 1;
}
if ($a->score > $b->score) {
return -1;
}
return 0;
});
print_r($data);
This manual comparison returns 1 if the first element should come after the second, -1 if it should come before, and 0 if they are equal. While this works, it is verbose. PHP allows you to simplify this using nullsort logic or by directly returning the result of subtraction. For descending order specifically, you can reverse the comparison logic:
usort($data, function ($a, $b) {
return $b->score - $a->score;
});
This single line effectively sorts the array from highest to lowest score. However, there is a critical trade-off to consider regarding data types. The json_decode function defaults to returning objects when the second argument is false (or omitted). If you are using PHP 8.1 or later, you might prefer decoding into an associative array instead of objects to avoid strict type errors or to access properties via string keys, which can sometimes be more robust in dynamic environments.
Alternatively, if you are working within the Laravel ecosystem, the Arr::sortByDesc helper provides a cleaner syntax that abstracts away the comparison logic entirely. This is particularly useful when maintaining readability and reducing boilerplate code in larger applications. You can pass the decoded array to this helper along with the key name:
use Illuminate\Support\Arr;
$scores = Arr::sortByDesc($data, 'score');
This approach not only sorts by score but also maintains the stability of the sort if two items have identical scores, preserving their original relative order.
Performance and Stability Considerations
When choosing between usort and helper functions like Arr::sortByDesc, consider the performance implications on large datasets. usort operates in O(n log n) time complexity, which is standard for comparison-based sorting. The overhead of a closure in usort is generally negligible unless you are sorting millions of records in a tight loop.
Another common pitfall involves floating-point precision. If your score values were decimal numbers rather than integers, subtracting them ($b->score - $a->score) can sometimes lead to precision errors where 0 becomes something like -4.9e-015. In such cases, it is safer to stick with the explicit comparison logic or use a library that handles arbitrary precision arithmetic.
Finally, ensure that the keys you are sorting by exist in every object. If one object lacks the score property, PHP will throw a fatal error when accessing $a->score. Always validate your data structure before attempting to sort it if the source is untrusted or dynamically generated.