22

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,391
  • 2
  • 23
  • 39

2 Answers2

72

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
  • 32,252
  • 11
  • 87
  • 108
5

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

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
RJParikh
  • 4,096
  • 1
  • 19
  • 36
  • 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 – Alive to die - Anant Jun 30 '16 at 07:46
  • ok i will keep in mind. Thanks for your advice @Anant – RJParikh Jun 30 '16 at 08:15