Custom array sorting with usort()
Another common use of callbacks is with PHP’s
usort()
function. This function lets you sort arrays using a sorting callback function that you write yourself. This is particularly handy if you need to sort an array of objects or associative arrays, since only you, as the coder, know the best way to sort such complex structures.
Let’s create an array of associative arrays, where each associative array has a
name
key and an age
key:$people = array( array( "name" => "Fred", "age" => 39 ), array( "name" => "Sally", "age" => 23 ), array( "name" => "Mary", "age" => 46 ) );
Now, say we want to sort the array in ascending order of age. We can’t use the regular PHP array sorting functions, since these don’t know anything about the
age
key. Instead, we can call usort()
and pass in an anonymous callback function that sorts the array by age, like this:usort( $people, function( $personA, $personB ) { return ( $personA["age"] < $personB["age"] ) ? -1 : 1; } ); print_r( $people );
This produces the result we want:
Array ( [0] => Array ( [name] => Sally [age] => 23 ) [1] => Array ( [name] => Fred [age] => 39 ) [2] => Array ( [name] => Mary [age] => 46 ) )
No comments:
Post a Comment