0

Possible Duplicates:
How to sort an array based on a specific field in the array?
sorting array based on inner-array key-value

How Sort array by inner array values?

One of the cases - need to sort according numbers(80,25,85, etc..): input:

array (
  0 => 
  array (
    'item1' => 80,
  ),
  1 => 
  array (
    'item2' => 25,
  ),
  2 => 
  array (
    'item3' => 85,
  ),
)

output:

array (
  0 => 
  array (
    'item2' => 25,
  ),
  1 => 
  array (
    'item1' => 80,
  ),
  2 => 
  array (
    'item3' => 85,
  ),
)

Thanks in advance

Community
  • 1
  • 1
gary
  • 1
  • 1
    Or this one: http://stackoverflow.com/questions/2426917/how-do-i-sort-a-multidimensional-array-by-one-of-the-fields-of-the-inner-array-in – hakre Jun 30 '11 at 12:55

2 Answers2

0

You need to use usort

$array = array (
  0 =>
  array (
    'item1' => 80,
  ),
  1 =>
  array (
    'item2' => 25,
  ),
  2 =>
  array (
    'item3' => 85,
  ),
);

function my_sort_cmp($a, $b) {
    reset($a);
    reset($b);
    return current($a) < current($b) ? -1 : 1;
}

usort($array, 'my_sort_cmp');

print_r($array);

Output:

(
    [0] => Array
        (
            [item2] => 25
        )

    [1] => Array
        (
            [item1] => 80
        )

    [2] => Array
        (
            [item3] => 85
        )

)
Dogbert
  • 200,802
  • 40
  • 378
  • 386
0

You need to use usort, a function that sorts arrays via a user defined function. Something like:

function cmp($a, $b)
{
    $a = reset($a); // get the first array elements
    $b = reset($b); // for comparison.
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

usort($yourArray,"cmp")

Compare this with the answer of one of the questions duplicates.

Community
  • 1
  • 1
hakre
  • 184,866
  • 48
  • 414
  • 792