⬆️ ⬇️

Sorting objects in PHP

In PHP, there are so many different functionalities for working with arrays, but for objects it is sometimes necessary to reinvent bicycles again and again. So which bike is today?

The other day, a seemingly elementary task arose - sorting the set of objects obtained from the database in the form of a rowset. The sorting functions work with arrays and they do not care about objects. This is where the sorting function comes to the rescue using a user-defined function - usort (array & $ array, callback $ cmp_function). We can make our operation of comparing objects the second argument.

Suppose we have received from the database many cities in the world. 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 do this for three different requests to the database. So proceed to the implementation of 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 is ready, but closures are being asked for 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 all this into a function and make the identifier a variable, then we get a quite useful function of 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 .


')

Source: https://habr.com/ru/post/101181/



All Articles