1

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?

Activist
  • 186
  • 2
  • 11

2 Answers2

4
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");
Maerlyn
  • 32,079
  • 17
  • 92
  • 82
  • +1. Just to elaborate for the person asking the question, this uses PHP's user defined sort referenced here: http://www.php.net/manual/en/function.usort.php – Fosco Aug 10 '10 at 14:19
4

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.

Gumbo
  • 594,236
  • 102
  • 740
  • 814