Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have an array and need to be sorted (based on id):

Array
(
   [0] => Array
    (
        [qty] => 1
        [id] => 3
        [name] => Name1
        [sku] => Model 1
        [options] => 
        [price] => 100.00
    )
   [1] => Array
    (
        [qty] => 2
        [id] => 1
        [name] => Name2
        [sku] => Model 1
        [options] => Color: <em>Black (+10$)</em>. Memory: <em>32GB (+99$)</em>. 
        [price] => 209.00
    )

)

Is it possible to sort my array to get output (id based)?

 Array
    (
    [0] => Array
      (
        [qty] => 2
        [id] => 1
        [name] => Name2
        [sku] => Model 1
        [options] => Color: <em>Black (+10$)</em>. Memory: <em>32GB (+99$)</em>. 
        [price] => 209.00
      ) 
    [1] => Array
      (
        [qty] => 1
        [id] => 3
        [name] => Name1
        [sku] => Model 1
        [options] => 
        [price] => 100.00
      )
 )

Thanks!

share|improve this question

marked as duplicate by DrColossos, Joe, George, Yoshi, Barmar Jun 27 '13 at 10:20

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
This should answer your question: stackoverflow.com/questions/96759/… –  Joe Jun 27 '13 at 10:19
    
This also looks like a result from a database query. Isn't this better handled by using an ORDER BY clause in the query? –  Phylogenesis Jun 27 '13 at 10:20

2 Answers 2

up vote 1 down vote accepted

Try like

$id_arr = array();
foreach ($my_arr as $key => $value)
{
    $id_arr[$key] = $value['id'];
}
array_multisort($id_arr, SORT_DESC, $my_arr);

You can also place SORT_ASC for assending order.Better you add ORDER BY id to the query through which you are getting this array of results

share|improve this answer
function cmp($a, $b) {
        return $a["id"] - $b["id"];
}
usort($arr, "cmp");//$arr is the array to sort
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.