laravel 按日期对数组进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37567751/
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
laravel sort an array by date
提问by Cruzito
hello friends I have an array that looks like this:
你好朋友我有一个看起来像这样的数组:
array:3 [▼
0 => array:6 [▼
"date" => "2016-05-31 15:08:33"
0 => "31 May 16"
1 => "aze"
2 => "2"
3 => "hi"
4 => "487841464704194.jpg"
]
1 => array:6 [▼
"date" => "2016-05-31 15:26:09"
0 => "31 May 16"
1 => "aze"
2 => "2"
3 => "hey"
4 => "487841464704194.jpg"
]
2 => array:6 [▼
"date" => "2016-06-01 11:33:06"
0 => "01 Jun 16"
1 => "aze"
2 => "2"
3 => "Dm me please"
4 => "487841464704194.jpg"
]
]
My goal is to sort it by the date
. So from new to old.
我的目标是按date
. 所以从新到旧。
If tried this:
如果试过这个:
$comarrSorted = $comarr->sortByDesc('date');
dd($comarrSorted);
But I get this nasty error:
但是我收到了这个令人讨厌的错误:
Call to a member function sortByDesc() on array
Anyone can help me out? I guess the error is caused because it's a collection function? Is it not possible to sort my array with this function?
任何人都可以帮助我吗?我猜这个错误是因为它是一个集合函数引起的?不能用这个函数对我的数组进行排序吗?
Many Thanks in advance!
提前谢谢了!
采纳答案by Hiren Makwana
you have to create your own function
你必须创建自己的函数
array_sort_by_column($array, 'date');
function array_sort_by_column(&$array, $column, $direction = SORT_ASC) {
$reference_array = array();
foreach($array as $key => $row) {
$reference_array[$key] = $row[$column];
}
array_multisort($reference_array, $direction, $array);
}
回答by Chukwuemeka Inya
You can convert to a collection
, call the sortBy()
and the convert back to an array
all on one line.
您可以转换为 a collection
,调用 thesortBy()
并将转换回array
all 一行。
$sortedArr = collect($array)->sortBy('date')->all();
回答by Hiren Makwana
You can use usort()
with custom comarison function.
您可以使用usort()
自定义comarison功能。
function sortByDate($arr1, $arr2)
{
$tmp1 = strtotime($arr1['date']);
$tmp2 = strtotime($arr2['date']);
return $tmp1 - $tmp2;
}
usort($array, 'date');