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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38116513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:29:46  来源:igfitidea点击:

How to sort an assocoative array in php Laravel

phplaravelsorting

提问by Vikash

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

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

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

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

回答by Jerodev

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

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

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

回答by RJParikh

Using array_multisort().

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

现场演示:点击这里