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

2022-08-30 20:17:19

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

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

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

答案 1

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

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

答案 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
        )

)

现场演示 : 点击这里


推荐