[英]sorting a config variable based on date in laravel
I have a config variable that uses a foreach loop to print out all the objects. 我有一个配置变量,它使用foreach循环打印出所有对象。 Is there a way to sort what prints out based on date? 有没有办法根据日期对打印出来的内容进行排序? Here is my code for printing out the object. 这是我打印出对象的代码。 I want to sort it based on $press['date']
我想根据$press['date']
对其进行排序
@foreach (config('constants.pressMetadata') as $press)
<div>
<p id="quote">{{ $press['title'] }}</p>
<div class="more label"><a id="link" href="{{$press['url']}}">-{{$press['company']}}: {{$press['date']}}</a></div>
<hr>
</div>
@endforeach
Here is constants.pressMetadata
: 这是constants.pressMetadata
:
'pressMetadata'=>[
"AARP" => [
"id" => 1,
"company" => "AARP",
"title" => "Updating Your Résumé for the Digital Age",
"url" => "http://www.aarp.org/work/job-hunting/info-2016/give-resume-a-digital-reboot.html",
"date" => "Sep 9, 2016"
],
"Business Insider" => [
"id" => 2,
"company" => "Business Insider",
"title" => "8 things you should always include on your résumé",
"url" => "http://www.businessinsider.com/what-to-always-include-on-your-resume-2016-1",
"date" => "Jan 28, 2016"
],
"Morning Journal" => [
"id" => 3,
"company" => "Morning Journal",
"title" => "5 things you missed: Google updates search, Jobscan and more",
"url" => "http://www.morningjournal.com/article/MJ/20140124/NEWS/140129366",
"date" => "Jan 24, 2014"
],
],
You should be able to use Laravel's collections to make this pretty easy. 您应该能够使用Laravel的集合来实现这一点。 Wrap the call to config()
in a call to collect()
, and then use the sortBy()
method on the collection to sort the records by the strtotime()
value of the 'date' key. 在对collect()
的调用中包含对config()
的调用,然后对集合使用sortBy()
方法,通过'date'键的strtotime()
值对记录进行排序。 Use the sortByDesc()
method if you want to sort the other way. 如果要以其他方式排序,请使用sortByDesc()
方法。
@foreach (collect(config('constants.pressMetadata'))->sortBy(function ($press) { return strtotime($press['date']); }) as $press)
You can use the usort
function of PHP. 您可以使用PHP的usort
函数。
The following code is taken from the PHP manual and changed to reflect your needs 以下代码取自PHP手册,并进行了更改以反映您的需求
function cmp($a, $b)
{
if (strtotime($a['date']) == strtotime($b['date'])) {
return 0;
}
return (strtotime($a['date']) < strtotime($b['date'])) ? -1 : 1;
}
usort(config('constants.pressMetadata'), "cmp");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.