views:

62

answers:

4

This should be really simple, but what is the way to go on this. I want to sort an multidimensional array by a key, like this:

Array (
[0] => Array
    (
        [iid] => 1
        [invitee] => 174
        [nid] => 324343
        [showtime] => 2010-05-09 15:15:00
        [location] => 13
        [status] => 1
        [created] => 2010-05-09 15:05:00
        [updated] => 2010-05-09 16:24:00
    )

[1] => Array
    (
        [iid] => 1
        [invitee] => 220
        [nid] => 21232
        [showtime] => 2010-05-09 15:15:00
        [location] => 12
        [status] => 0
        [created] => 2010-05-10 18:11:00
        [updated] => 2010-05-10 18:11:00
    ))

Say i want to sort this by [status], how would I achieve this? Thanks in advance!

+1  A: 

usort function is what you're looking for:

<?php
    function cmp($a, $b) {
        return $b["status"] - $a["status"];
    }

    $sorted = usort($your_array, "cmp");
    var_dump($sorted);
?>
Tomasz Tybulewicz
+1  A: 
//define a comparison function
function cmp($a, $b) {
    if ($a['status'] == $b['status']) {
        return 0;
    }
    return ($a['status'] < $b['status']) ? -1 : 1;
}

usort($array, "cmp");

That should do what you want, you can alter the comparison function to sort on whatever key you want.

Austin Fitzpatrick
A: 

Try this

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

usort($data_array, "cmp_by_status");
Toader Mihai Claudiu
A: 

See array_multisort example 3

kalkin