Sorting Multidimensional Arrays
array('name' => 'Name', 'grade' => xx.x)
$students = array(
256 => array('name' => 'Jon', 'grade' => 98.5),
2 => array('name' => 'Vance', 'grade' => 85.1),
9 => array('name' => 'Stephen', 'grade' => 94.0),
364 => array('name' => 'Steve', 'grade' => 85.1),
68 => array('name' => 'Rob', 'grade' => 74.6)
);
// Name sorting function:
function name_sort($x, $y) {
return strcasecmp($x['name'], $y['name']);
}
// Grade sorting function:
// Sort in DESCENDING order!
function grade_sort($x, $y) {
return ($x['grade'] < $y['grade']);
}
// Print the array as is:
echo 'Array As Is ' . print_r($students, 1) . ' ';
// Sort by Name:
uasort($students, 'name_sort');
echo 'Array Sort By Name ' . print_r($students, 1) . ' ';
// Sort by grade:
uasort($students, 'grade_sort');
echo 'Array Sort By Grade ' . print_r($students, 1) . ' ';
?>