我要在日期字段订购包含客户评论的数组。从最新日期到最早的日期。
$testimonials = array:356 [▼
0 => array:4 [▼
"comment" => "blahblahblahblahblah"
"name" => "John"
"date" => "12/04/2019"
]
1 => array:4 [▼
"comment" => "blah blah blah blah blah"
"name" => "Franky V"
"date" => "13/05/2019"
]
2 => array:4 [▼
"comment" => "lololololol"
"name" => "Peter"
"date" => "06/03/2020"
]
3 => array:4 [▼
"comment" => "blahblahblahblahblahblahblahblahblah"
"name" => "Hugo"
"date" => "24/01/2019"
]
....
我想得到这个结果:
$testimonials = array:356 [▼
0 => array:4 [▼
"comment" => "lololololol"
"name" => "Peter"
"date" => "06/03/2020"
]
1 => array:4 [▼
"comment" => "blah blah blah blah blah"
"name" => "Franky V"
"date" => "13/05/2019"
]
2 => array:4 [▼
"comment" => "blahblahblahblahblah"
"name" => "John"
"date" => "12/04/2019"
]
3 => array:4 [▼
"comment" => "blahblahblahblahblahblahblahblahblah"
"name" => "Hugo"
"date" => "24/01/2019"
]
如何在Laravel控制器中或使用PHP做到这一点?
编辑:我正在尝试使用usort,但我弄错了
public function getTrollingDates($testimonials) {
$currentdate = new DateTime();
$currentdate = $currentdate->format('Y-m-d');
foreach($testimonials as &$testimonial) {
$testimonial['date'] = $this->getRandomDate('2019-01-01',$currentdate);
}
$testimonials = usort($testimonials, 'compare');
return $testimonials;
}
public function compare($a, $b) {
return strtotime($b['date']) - strtotime($a['date']) ;
}
这会向我返回此错误:
usort() expects parameter 2 to be a valid callback, function 'compare' not found or invalid function name
答案 0 :(得分:0)
假设$testimonials
是集合对象,则可以使用sortByDesc()
按日期降序排序。
<?php
$testimonials = $testimonials->sortByDesc(function($a){
return DateTime::createFromFormat('d/m/Y',$a['date']);
});
dd($testimonials);
答案 1 :(得分:0)
在Laravel
中,您可以这样做:
$array = collect($testimonials)->sortBy('date')->reverse()->toArray();
在PHP
中,您可以使用usort
来达到相同的目的
function compare($a, $b) {
// if you want to sort by ascending
return strtotime($b['date']) - strtotime($a['date']) ;
//if you want to sort by descending order
// return strtotime($a['date']) - strtotime($b['date']) ;
}
usort($my_array, 'compare');