PHP sort an array of array [duplicate]
I have the folloring array structure:
$list = array();
$element1 = array('start' => '10', 'end' => '15');
$element2 = array('start' => '1', 'end' => '5');
$list[] = $element1;
$list[] = $element2;
Every element in start
and end
are numeric only.
I would like to sort $list
by start
values. How can I do that effectivly?
You can use usort
with this comparison function:
function cmp($a, $b) {
if ($a['start'] == $b['start']) {
return $a['end'] - $b['end'];
} else {
return $a['start'] - $b['start'];
}
}
With this comparison function the elements are ordered by their start value first and then by their end value.
function cmp($a, $b)
{
if ($a['start'] == $b['start']) {
return 0;
}
return ($a['start'] < $b['start']) ? -1 : 1;
}
$list = array();
$element1 = array('start' => '10', 'end' => '15');
$element2 = array('start' => '1', 'end' => '5');
$list[] = $element1;
$list[] = $element2;
usort($list, "cmp");
精彩评论