Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an assocoative array in php Laravel [duplicate]

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,
      )
  )
like image 671
Vikash Avatar asked Jun 30 '16 07:06

Vikash


2 Answers

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();
like image 165
Jerodev Avatar answered Oct 17 '22 12:10

Jerodev


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

like image 4
RJParikh Avatar answered Oct 17 '22 11:10

RJParikh