Multiple Sorts in an Array

I have the following array:

Array
(
[0] => Array
    (
        [note] => test
        [year] => 2011
        [type] => football
    )

[1] => Array
    (
        [note] => test1
        [year] => 2010
        [type] => basket
    )

[2] => Array
    (
        [note] => test2
        [year] => 2012
        [type] => football
    )

[3] => Array
    (
        [note] => test3
        [year] => 2009
        [type] => basket
    )

[4] => Array
    (
        [note] => test4
        [year] => 2010
        [type] => football
    )

)

And I would like to sort it first by another array by type:

For instance: $sort = array('football','basket');

And then over the years.

How can i do this?

Thank.

The required conclusion should be:

Array
(
[2] => Array
    (
        [note] => test2
        [year] => 2012
        [type] => football
    )
[0] => Array
    (
        [note] => test
        [year] => 2011
        [type] => football
    )
[4] => Array
    (
        [note] => test4
        [year] => 2010
        [type] => football
    )

[1] => Array
    (
        [note] => test1
        [year] => 2010
        [type] => basket
    )

[3] => Array
    (
        [note] => test3
        [year] => 2009
        [type] => basket
    )

)

I do not mind if we reset the index values.

Thank.

+5
source share
3 answers

Use array_multisort. Assuming your array is $arr:

foreach($arr as $key=>$row) {
    $type[$key] = $row['type'];
    $year[$key] = $row['year'];
}
array_multisort($type, SORT_ASC, $year, SORT_ASC, $arr);

To use a dependent array defining the type order, you can do:

$sortBy = array('football','basket');
foreach($arr as $key=>$row) {
    $type[$key] = array_search($row['type'],$sortBy);
    $year[$key] = $row['year'];
}
array_multisort($type, SORT_ASC, $year, SORT_ASC, $arr);

Link example:

http://codepad.org/qhZCpbZE

+2
source

Requires a PHP version that supports closing on as-is startup

. , .

$sortBy = array('football', 'basket');

.

, , $sortBy .

usort($a, function($a, $b) use ($sortBy) {
    if ($a['type'] == $b['type']) {
        return ($b['year'] - $a['year']);
    }
    $typeOrder = array_flip($sortBy);
    return $typeOrder[$a['type']] - $typeOrder[$b['type']];
});
+4

Use usort

function byType($a, $b)
{
    if ($a['type'] == $b['type']) {
        return 0;
    }

    foreach(array('football','basket') as $type) {
        if ($a['type']=$type) return -1;
        if ($b['type']=$type) return 1;
    }

    return 0;
}


function byYear($a, $b)
{
    if ($a['year'] == $b['year']) {
        return 0;
    }
    return ($a['year'] < $b['year']) ? -1 : 1;
}

usort($array,"byType");
usort($array,"byYear");
+1
source

All Articles