根据laravel中的日期对配置变量进行排序

时间:2017-04-14 23:49:44

标签: php laravel sorting multidimensional-array laravel-blade

我有一个配置变量,它使用foreach循环打印出所有对象。有没有办法根据日期对打印出来的内容进行排序? 这是我打印出对象的代码。我想根据$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

以下是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"
      ],
],

2 个答案:

答案 0 :(得分:1)

你应该可以使用Laravel的系列来实现这一点。在调用config()时将呼叫包裹到collect(),然后使用集合上的sortBy()方法按“日期”键的strtotime()值对记录进行排序。如果您想以其他方式排序,请使用sortByDesc()方法。

@foreach (collect(config('constants.pressMetadata'))->sortBy(function ($press) { return strtotime($press['date']); }) as $press)

Documentation here

答案 1 :(得分:0)

您可以使用PHP的usort功能。

以下代码摘自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");