如何在php Laravel中对一个关联数组进行排序

时间:2016-06-30 07:27:01

标签: php laravel sorting

我想根据count以降序对此数组进行排序。这是我的array

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

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

2 个答案:

答案 0 :(得分:21)

如果您使用的是标签建议的Laravel,您可以使用集合来操作这样的数组。例如:

$array = collect($array)->sortBy('count')->reverse()->toArray();

答案 1 :(得分:2)

使用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);    

节目输出

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

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

)

现场演示:Click Here