5

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!

John Carter
  • 50,377
  • 25
  • 100
  • 137
Eelke
  • 2,149
  • 1
  • 19
  • 26
  • this has been asked lots of times - see http://stackoverflow.com/questions/777597/sorting-an-associative-array-in-php , http://stackoverflow.com/questions/96759/how-do-i-sort-a-multidimensional-array-in-php , http://stackoverflow.com/questions/96759/how-do-i-sort-a-multidimensional-array-in-php for a start – John Carter May 10 '10 at 17:12

5 Answers5

7
//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
  • 6,575
  • 2
  • 23
  • 21
2

Try this : Using array_multisort

$sort = array();
foreach($your_array as $k=>$v) {
    $sort['status'][$k] = $v['status'];
}

array_multisort($sort['status'], SORT_DESC, $your_array);


echo "<pre>";
print_r($your_array);

Ref: http://php.net/manual/en/function.array-multisort.php

Prasanth Bendra
  • 26,567
  • 8
  • 48
  • 67
1

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
  • 7,869
  • 3
  • 42
  • 41
0

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");
Mihai Toader
  • 11,551
  • 1
  • 27
  • 33
0

I have added this answer at Sort multi-dimensional array by specific key sort the array specific key to sorting array value.

function sortBy($field, &$array, $direction = 'asc')
{
    usort($array, create_function('$a, $b', '
        $a = $a["' . $field . '"];
        $b = $b["' . $field . '"];

        if ($a == $b)
        {
            return 0;
        }

        return ($a ' . ($direction == 'desc' ? '>' : '<') .' $b) ? -1 : 1;
    '));

    return true;
}

Call this function by specific array key

sortBy('status',   $array);
Community
  • 1
  • 1
Kishan Chauhan
  • 982
  • 1
  • 8
  • 16