0

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!

XTRUST.ORG
  • 3,280
  • 4
  • 34
  • 60
  • This should answer your question: http://stackoverflow.com/questions/96759/how-do-i-sort-a-multidimensional-array-in-php – 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 Answers2

1

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

GautamD31
  • 28,552
  • 10
  • 64
  • 85
1
function cmp($a, $b) {
        return $a["id"] - $b["id"];
}
usort($arr, "cmp");//$arr is the array to sort
웃웃웃웃웃
  • 11,829
  • 15
  • 59
  • 91