Question

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!

Was it helpful?

Solution

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

OTHER TIPS

function cmp($a, $b) {
        return $a["id"] - $b["id"];
}
usort($arr, "cmp");//$arr is the array to sort
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top