$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)
);
function grade_sort($x,$y){
return ($x['grade'] < $y['grade']);
}
uasort ($students, 'grade_sort');
i am a new learner of php,i can’t understand the above code well. could i change this return ($x['grade'] < $y['grade']); to return $x < $y; if not, why? thank you
No.
$xand$ywill be one of the arrays inside$students.E.g.
$xmay bearray('name' => 'Jon', 'grade' => 98.5)and
$ymay bearray('name' => 'Vance', 'grade' => 85.1).So
return $x < $ydoesn’t make sense.That code isn’t very good though. The comparison function
grade_sorttakes two elements at a time and should return0if both elements are considered equal, a negative number if the first is lower and a positive number if the second lower. Yours returnstrueorfalse. The correct code would be:uasortsimply keeps calling this function with two different elements until it is satisfied it knows which element is larger than which and has sorted them all.