20

I want to sort this array based on count in descending order. here is my array

array(   
   46 => 
      array (
       'name' => 'HSR Layout',
       'url' => 'hsr-layout',
       'count' => 2,
      ),

   37 => 
      array (
       'name' => 'Electronic City',
       'url' => 'electronic-city',
       'count' => 3,
      )
  )
Vikash
  • 3,216
  • 2
  • 19
  • 35

2 Answers2

64

If you are using Laravel, which your tag suggests, you can use collections to manipulate arrays like this. For example:

$array = collect($array)->sortBy('count')->reverse()->toArray();
Jerodev
  • 31,061
  • 11
  • 83
  • 102
3

Using array_multisort().

$array = array(   
   46 => 
      array (
       'name' => 'HSR Layout',
       'url' => 'hsr-layout',
       'count' => 2,
      ),

   37 => 
      array (
       'name' => 'Electronic City',
       'url' => 'electronic-city',
       'count' => 3,
      )
  );

$price = array();
foreach ($array as $key => $row)
{
    $count[$key] = $row['count'];
}
array_multisort($count, SORT_DESC, $array);

print_r($array);    

Program Output

Array
(
    [0] => Array
        (
            [name] => Electronic City
            [url] => electronic-city
            [count] => 3
        )

    [1] => Array
        (
            [name] => HSR Layout
            [url] => hsr-layout
            [count] => 2
        )

)

Live demo : Click Here

Anant Kumar Singh
  • 68,309
  • 10
  • 50
  • 94
RJParikh
  • 4,110
  • 1
  • 18
  • 35
  • check above code its useful to you for your issue. @Vikash – RJParikh Jun 30 '16 at 07:40
  • 1
    This is much too complicated, a simple `usort` with a `count` comparing lambda-function is all that's needed here – Tom Regner Jun 30 '16 at 07:43
  • @RuchishParikh as OP says he is using laravel your answer is not useful for him. Also a complex answer is not needed if you want to give it too also:- http://stackoverflow.com/questions/2699086/sort-multi-dimensional-array-by-value – Anant Kumar Singh Jun 30 '16 at 07:46
  • ok i will keep in mind. Thanks for your advice @Anant – RJParikh Jun 30 '16 at 08:15