Created
February 14, 2011 23:07
-
-
Save lukemorton/826779 to your computer and use it in GitHub Desktop.
sorting two dimensions in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<pre><?php | |
// A nice simple 2 dimensional array | |
$people = array( | |
// array($name, $age) | |
array('Jim', 20), | |
array('Betty', 50), | |
array('Bob', 35), | |
array('Rob', 22), | |
array('Rachel', 40), | |
); | |
/** | |
* A custom sort function as per http://uk.php.net/manual/en/function.usort.php | |
*/ | |
function order_by_age_asc($a, $b) | |
{ | |
// If age of $a is the same as age from $b | |
if ($a[1] === $b[1]) { | |
return 0; | |
} | |
// If $a age is less that $b age -1 otherwise +1 | |
// This is used to order each array from lowest to highest | |
return ($a[1] < $b[1]) ? -1 : 1; | |
} | |
// This will print an array of people sorted by age ASC | |
usort($people, 'order_by_age_asc'); | |
print_r($people); | |
/** | |
* A custom sort function as per http://uk.php.net/manual/en/function.usort.php | |
*/ | |
function order_by_age_desc($a, $b) | |
{ | |
// If age of $a is the same as age from $b | |
if ($a[1] === $b[1]) { | |
return 0; | |
} | |
// If $a age is less that $b age +1 otherwise -1 | |
// This is used to order each array from highest to lowest | |
return ($a[1] < $b[1]) ? 1 : -1; | |
} | |
// This will print an array of people sorted by age DESC | |
usort($people, 'order_by_age_desc'); | |
print_r($people); | |
// Default oldest person to first of the array | |
$oldest = $people[0]; | |
// Default youngest person to first of the array | |
$youngest = $people[0]; | |
foreach ($people as $_person) | |
{ | |
// If this persons ages is greater than the oldest | |
// make this the oldest | |
if ($oldest < $_person[1]) | |
{ | |
$oldest = $_person; | |
} | |
// Also check if lower than the youngest | |
if ($youngest > $_person[1]) | |
{ | |
$youngest = $_person; | |
} | |
} | |
print_r($oldest); | |
print_r($youngest); |
Thanks for pointing that function out :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The manual has an example that does exactly what you are doing here but using
array_multisort()
.http://php.net/array_multisort
The custom sort functions save the whole array-preparing though.
btw "shorting" in the description