Sorting Objects in an Array by Property
When dealing with arrays of objects, you might encounter the need to organize them based on a specific field or property. This article addresses the question of how to sort an array of objects by a specified field, such as name or count.
To accomplish this, PHP provides us with the usort function. It takes an array as its first argument and a callable as its second argument, which serves as a comparison function. This comparison function should return an integer indicating the result of the comparison: -1 if the first object should come before the second, 0 if they're equal, and 1 if the second object should come before the first.
Let's consider an example with an array of objects:
$array = [ (object) ['name' => 'Mary Jane', 'count' => 420], (object) ['name' => 'Johnny', 'count' => 234], (object) ['name' => 'Kathy', 'count' => 4354], ];
To sort this array by the name field, we can define a comparison function as follows:
function cmp($a, $b) { return strcmp($a->name, $b->name); }
Now we can use usort to sort the array:
usort($array, 'cmp');
This will sort the array in ascending order of the name field.
Alternative Approaches
In addition to the traditional comparison function, PHP offers various alternative approaches for sorting:
usort($array, function($a, $b) { return strcmp($a->name, $b->name); });
class MyComparator { public function cmp($a, $b) { return strcmp($a->name, $b->name); } } $array = usort($array, [new MyComparator(), 'cmp']);
usort($array, fn($a, $b) => strcmp($a->name, $b->name));
Comparing Numeric Fields
When comparing numeric fields, such as the count field in our example, you can use the following comparison function:
fn($a, $b) => $a->count - $b->count
Alternatively, PHP 7 introduced the Spaceship operator (<=>) which can be used for such comparisons, e.g.:
fn($a, $b) => $a->count <=> $b->count
The above is the detailed content of How to Sort an Array of Objects by a Specific Property in PHP?. For more information, please follow other related articles on the PHP Chinese website!