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!

2
  • This should answer your question: stackoverflow.com/questions/96759/… Commented Jun 27, 2013 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? Commented Jun 27, 2013 at 10:20

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.