Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array of objects by object fields

How can I sort this array of objects by one of its fields, like name or count ?

  Array (     [0] => stdClass Object         (             [ID] => 1             [name] => Mary Jane             [count] => 420         )      [1] => stdClass Object         (             [ID] => 2             [name] => Johnny             [count] => 234         )      [2] => stdClass Object         (             [ID] => 3             [name] => Kathy             [count] => 4354         )     .... 
like image 239
Alex Avatar asked Nov 26 '10 03:11

Alex


People also ask

How do you sort an array of objects?

To sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.

How do you sort an array of objects based on the key?

const arr1 = ['d','a','b','c'] ; const arr2 = [{a:1},{c:3},{d:4},{b:2}]; We are required to write a JavaScript function that accepts these two arrays. The function should sort the second array according to the elements of the first array.


1 Answers

Use usort, here's an example adapted from the manual:

function cmp($a, $b) {     return strcmp($a->name, $b->name); }  usort($your_data, "cmp"); 

You can also use any callable as the second argument. Here are some examples:

  • Using anonymous functions (from PHP 5.3)

      usort($your_data, function($a, $b) {return strcmp($a->name, $b->name);}); 
  • From inside a class

      usort($your_data, array($this, "cmp")); // "cmp" should be a method in the class 
  • Using arrow functions (from PHP 7.4)

      usort($your_data, fn($a, $b) => strcmp($a->name, $b->name)); 

Also, if you're comparing numeric values, fn($a, $b) => $a->count - $b->count as the "compare" function should do the trick, or, if you want yet another way of doing the same thing, starting from PHP 7 you can use the Spaceship operator, like this: fn($a, $b) => $a->count <=> $b->count.

like image 111
cambraca Avatar answered Oct 01 '22 19:10

cambraca