开发者

PHP sort an array of array [duplicate]

This question already has answers here: How can I sort arrays and data开发者_运维技巧 in PHP? (14 answers) Closed 8 years ago.

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");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜