Sort objects in PHP
PHP has so many different functionalities for working with arrays, but for objects you sometimes have to reinvent the wheel again and again. So which bike is it today?
The other day, a completely seemingly elementary task arose - to sort a lot of objects received from a database in the form of a rowset. Sorting functions work with arrays and they don't care about objects. Here, a sorting function comes to the rescue using a user-defined function - usort (array & $ array, callback $ cmp_function). The second argument is precisely what we can do our object comparison operation.
Let's say we got a lot of cities in the world from the database. For one task, we need to sort these cities by population, for another - by average annual temperature, for the third - in alphabetical order by city name. Do not make three different queries to the database for this. So let's get started with sorting.
In general, it’s ready, but closures are asked here, right?
And if we wrap it all up in a function and make the identifier a variable, then we get a quite useful function for sorting objects
The other day, a completely seemingly elementary task arose - to sort a lot of objects received from a database in the form of a rowset. Sorting functions work with arrays and they don't care about objects. Here, a sorting function comes to the rescue using a user-defined function - usort (array & $ array, callback $ cmp_function). The second argument is precisely what we can do our object comparison operation.
Let's say we got a lot of cities in the world from the database. For one task, we need to sort these cities by population, for another - by average annual temperature, for the third - in alphabetical order by city name. Do not make three different queries to the database for this. So let's get started with sorting.
<?php
usort($citiesForSort, 'sortByPopulation');
function sortByPopulation($city1, $city2){
if($city1->Population == $city2->Population)
return 0;
return ($city1->Population > $city2->Population) ? -1 : 1;
}
?>
* This source code was highlighted with Source Code Highlighter.
In general, it’s ready, but closures are asked here, right?
<?php
usort($citiesForSort, function($city1,$city2){
if($city1->Population == $city2->Population) return 0;
return ($city1->Population > $city2->Population) ? -1 : 1;});
?>
* This source code was highlighted with Source Code Highlighter.
And if we wrap it all up in a function and make the identifier a variable, then we get a quite useful function for sorting objects
<?php
function sortObjectSetBy($objectSetForSort, $sortBy){
usort($objectSetForSort, function($object1,$object2) use ($sortBy){
if($object1->$sortBy == $object2->$sortBy) return 0;
return ($object1->$sortBy > $object2->$sortBy) ? -1 : 1;});
return $objectSetForSort;
}
?>
* This source code was highlighted with Source Code Highlighter.