tags:

views:

28

answers:

2

Hello!

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?

+3  A: 
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
+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
+2  A: 

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