Php sort object by parameter

PHP usort

Summary: in this tutorial, you’ll learn how to use the PHP usort() function to sort an array using a user-defined comparison function.

Introduction to the PHP usort() function

So far, you learned how to sort an array using a built-in comparison operator.

For example, when you use the sort() function to sort an array of numbers, PHP uses the built-in comparison operator to compare the numbers.

To specify a custom comparison function for sorting, you use the usort() function:

usort(array &$array, callable $callback): boolCode language: PHP (php)

The usort() function has two parameters:

The usort() function returns true on success or false or failure.

The $callback has the following syntax:

callback(mixed $x, mixed $y): intCode language: PHP (php)

The $callback function has two parameters which are the array elements to compare.

The $callback function compares two elements ( $x and $y ) and returns an integer value:

  • zero (0) means $x is equal to $y .
  • a negative number means $x is before $y .
  • a positive number means $x is after $y .

PHP usort() function examples

Let’s take some examples of using the usort() function.

1) Using the PHP usort() function to sort an array of numbers

The following example illustrates how to use the usort() function to sort an array of numbers:

 $numbers = [2, 1, 3]; usort($numbers, function ($x, $y) < if ($x === $y) < return 0; > return $x < $y ? -1 : 1; >); print_r($numbers);Code language: PHP (php)
Array ( [0] => 1 [1] => 2 [2] => 3 ) Code language: PHP (php)
  • First, define an array of three numbers 2, 1, and 3.
  • Second, use the usort() function to sort the $numbers array. The callback function returns 0 if two numbers are equal, -1 if the first number is less than the second one, and 1 if the first number is greater than the second one.

To sort the elements of the array in descending order, you just need to change the logic in the comparison function like this:

 $numbers = [2, 1, 3]; usort($numbers, function ($x, $y) < if ($x === $y) < return 0; > return $x < $y ? 1 : -1; >); print_r($numbers);Code language: PHP (php)

If you use PHP 7 or newer, you can use the spaceship operator ( ) to make the code more concise:

The spaceship operator compares two expressions and returns -1, 0, or 1 when $x is respectively less than, equal to, or greater than $y . For example:

 $numbers = [2, 1, 3]; usort($numbers, function ($x, $y) < return $x $y; >); print_r($numbers);Code language: PHP (php)

If the callback is simple, you can use an arrow function like this:

 $numbers = [2, 1, 3]; usort($numbers, fn ($x, $y) => $x $y); print_r($numbers);Code language: PHP (php)

Note that PHP introduced the arrow functions since PHP 7.4.

2) Using the PHP usort() function to sort an array of strings by length

The following example uses the usort() function to sort an array of names by length:

 $names = [ 'Alex', 'Peter', 'John' ]; usort($names, fn($x,$y) => strlen($x) strlen($y)); var_dump($names);Code language: PHP (php)
Array(3) < [0]=> string(4) "Alex" [1]=> string(4) "John" [2]=> string(5) "Peter" >Code language: PHP (php)

3) Using the PHP usort() function to sort an array of objects

The following example uses the usort() function to sort an array of Person objects by the age property.

 class Person < public $name; public $age; public function __construct(string $name, int $age) < $this->name = $name; $this->age = $age; > > $group = [ new Person('Bob', 20), new Person('Alex', 25), new Person('Peter', 30), ]; usort($group, fn($x, $y) => $x->age $y->age); print_r($group);Code language: PHP (php)
Array ( [0] => Person Object ( [name] => Bob [age] => 20 ) [1] => Person Object ( [name] => Alex [age] => 25 ) [2] => Person Object ( [name] => Peter [age] => 30 ) )Code language: PHP (php)
  • First, define a Person class that has two properties: name and age .
  • Second, define the $group array that holds the Person objects.
  • Third, use the usort() function to sort the Person objects of the $group array. The usort() function uses a comparison function that compares the age of two Person objects.

If you want to sort the Person objects by name, you can compare the $name in the comparison like this:

usort($group, fn($x, $y) => $x->name $y->name);Code language: PHP (php)

Using a static method as a callback

The following example uses a static method of class as a callback for the usort() function:

 class Person < public $name; public $age; public function __construct(string $name, int $age) < $this->name = $name; $this->age = $age; > > class PersonComparer < public static function compare(Person $x, Person $y) < return $x->age $y->age; > > $group = [ new Person('Bob', 20), new Person('Alex', 25), new Person('Peter', 30), ]; usort($group, ['PersonComparer', 'compare']); print_r($group);Code language: PHP (php)

In this example, we define the PersonComparer class that contains the compare() static method.

The compare() static method compares two Person objects by age using the spaceship operator.

To use the compare() static method of the PersonComparer class as the callback the usort() function, you pass an array that contains two elements:

usort($group, ['PersonComparer', 'compare']);Code language: PHP (php)

The first element is the class name and the second one is the static method.

Summary

Источник

usort

Sorts array in place by values using a user-supplied comparison function to determine the order.

Note:

If two members compare as equal, they retain their original order. Prior to PHP 8.0.0, their relative order in the sorted array was undefined.

Note: This function assigns new keys to the elements in array . It will remove any existing keys that may have been assigned, rather than just reordering the keys.

Parameters

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Returning non-integer values from the comparison function, such as float , will result in an internal cast to int of the callback’s return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0 , which will compare such values as equal.

Return Values

Always returns true .

Changelog

Version Description
8.2.0 The return type is true now; previously, it was bool .
8.0.0 If callback expects a parameter to be passed by reference, this function will now emit an E_WARNING .

Examples

Example #1 usort() example

foreach ( $a as $key => $value ) echo » $key : $value \n» ;
>
?>

The above example will output:

The spaceship operator may be used to simplify the internal comparison even further.

foreach ( $a as $key => $value ) echo » $key : $value \n» ;
>
?>

Note:

Obviously in this trivial case the sort() function would be more appropriate.

Example #2 usort() example using multi-dimensional array

function cmp ( $a , $b )
return strcmp ( $a [ «fruit» ], $b [ «fruit» ]);
>

$fruits [ 0 ][ «fruit» ] = «lemons» ;
$fruits [ 1 ][ «fruit» ] = «apples» ;
$fruits [ 2 ][ «fruit» ] = «grapes» ;

foreach ( $fruits as $key => $value ) echo «\$fruits[ $key ]: » . $value [ «fruit» ] . «\n» ;
>
?>

When sorting a multi-dimensional array, $a and $b contain references to the first index of the array.

The above example will output:

$fruits[0]: apples $fruits[1]: grapes $fruits[2]: lemons

Example #3 usort() example using a member function of an object

class TestObj private string $name ;

function __construct ( $name )
$this -> name = $name ;
>

/* This is the static comparing function: */
static function cmp_obj ( $a , $b )
return strtolower ( $a -> name ) strtolower ( $b -> name );
>
>

$a [] = new TestObj ( «c» );
$a [] = new TestObj ( «b» );
$a [] = new TestObj ( «d» );

usort ( $a , [ TestObj ::class, «cmp_obj» ]);

foreach ( $a as $item ) echo $item -> name . «\n» ;
>
?>

The above example will output:

Example #4 usort() example using a closure to sort a multi-dimensional array

$array [ 0 ] = array( ‘key_a’ => ‘z’ , ‘key_b’ => ‘c’ );
$array [ 1 ] = array( ‘key_a’ => ‘x’ , ‘key_b’ => ‘b’ );
$array [ 2 ] = array( ‘key_a’ => ‘y’ , ‘key_b’ => ‘a’ );

function build_sorter ( $key ) return function ( $a , $b ) use ( $key ) return strnatcmp ( $a [ $key ], $b [ $key ]);
>;
>

usort ( $array , build_sorter ( ‘key_b’ ));

foreach ( $array as $item ) echo $item [ ‘key_a’ ] . ‘, ‘ . $item [ ‘key_b’ ] . «\n» ;
>
?>

The above example will output:

Example #5 usort() example using the spaceship operator

The spaceship operator allows for straightforward comparison of compound values across multiple axes. The following example will sort $people by last name, then by first name if the last name matches.

$people [ 0 ] = [ ‘first’ => ‘Adam’ , ‘last’ => ‘West’ ];
$people [ 1 ] = [ ‘first’ => ‘Alec’ , ‘last’ => ‘Baldwin’ ];
$people [ 2 ] = [ ‘first’ => ‘Adam’ , ‘last’ => ‘Baldwin’ ];

function sorter (array $a , array $b ) return [ $a [ ‘last’ ], $a [ ‘first’ ]] [ $b [ ‘last’ ], $b [ ‘first’ ]];
>

foreach ( $people as $person ) print $person [ ‘last’ ] . ‘, ‘ . $person [ ‘first’ ] . PHP_EOL ;
>
?>

The above example will output:

Baldwin, Adam Baldwin, Alec West, Adam

See Also

  • uasort() — Sort an array with a user-defined comparison function and maintain index association
  • uksort() — Sort an array by keys using a user-defined comparison function
  • The comparison of array sorting functions

User Contributed Notes 10 notes

As the documentation says, the comparison function needs to return an integer that is either «less than, equal to, or greater than zero». There is no requirement to restrict the value returned to -1, 0, 1.

usort ( $array , function( $a , $b ) if( $a -> integer_property > $b -> integer_property ) return 1 ;
>
elseif( $a -> integer_property < $b ->integer_property ) return — 1 ;
>
else return 0 ;
>
>);
?>

can be simplified to

usort ( $array , function( $a , $b ) return $a -> integer_property — $b -> integer_property ;
>);
?>

This of course applies to any comparison function that calculates an integer «score» for each of its arguments to decide which is «greater».

If you need to use usort with a key in the calling method, I wrote this as a utility:

function usort_comparison ( $obj , $method , $key ) $usorter = &new Usort ( $obj , $method , $key );
return array( $usorter , «sort» );
>

class Usort function __construct ( $obj , $method , $key ) $this -> obj = $obj ;
$this -> method = $method ;
$this -> key = $key ;
>
function sort ( $a , $b ) return call_user_func_array (array( $this -> obj , $this -> method ), array( $a , $b , $this -> key ));
>
>

class Foo $items = array( FooBar ( 13 ), FooBar ( 2 ));
public function sorter () usort ( $this — items , usort_comparison ( «Foo» , «_cmp» , «item» ));
>

public static function _cmp ( $a , $b , $key ) return strcasecmp ( $a -> $key , $b -> $key );
>

class FooBar public $item ;
function __construct ( $val ) $this -> item = $val ;
>
>

?>

~ simple example. but in the way I need to use it was the key was used in a switch statement to choose the different member of the object to compare against dynamically (as in, sort by x or y or z)

If you want to sort an array according to another array acting as a priority list, you can use this function.

function listcmp ( $a , $b )
<
global $order ;

foreach( $order as $key => $value )
<
if( $a == $value )
<
return 0 ;
break;
>

$order [ 0 ] = «first» ;
$order [ 1 ] = «second» ;
$order [ 2 ] = «third» ;

$array [ 0 ] = «second» ;
$array [ 1 ] = «first» ;
$array [ 2 ] = «third» ;
$array [ 3 ] = «fourth» ;
$array [ 4 ] = «second» ;
$array [ 5 ] = «first» ;
$array [ 6 ] = «second» ;

Источник

Читайте также:  Kotlin с чего начать изучение
Оцените статью