2017-04-14 36 views
3

我有一個配置變量,它使用foreach循環來打印出所有對象。有沒有辦法根據日期排序打印出來? 這是我打印出的對象的代碼。我想根據$press['date']根據laravel中的日期排序配置變量

@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" 
     ], 
], 
+0

[PHP按照含有日期的元素對多維數組進行排序]可能的重複(http://stackoverflow.com/questions/2910611/php-sort-a-multidimensional-array-by-element-containing-date) – mickmackusa

+0

你如果您在發佈問題前未搜索現有答案,則將其作爲資源貶值。看看有多少答案對你有幫助:http://stackoverflow.com/search?q=how+to+sort+multidimensional+array+by+date – mickmackusa

+0

downvoted因爲沒有顯示任何努力的研究和自我解決 – mickmackusa

回答

1

您應該能夠使用Laravel的集合,使這個很容易。在呼叫config()中調用collect(),然後使用集合上的sortBy()方法按「日期」鍵的strtotime()值排序記錄。如果您想以其他方式排序,請使用sortByDesc()方法。

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

Documentation here

+0

謝謝,我知道有這樣做的laravel方式,我只是找不到任何文件,沒有指向我香草的PHP – Aaron

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"); 
+0

如果您只是要複製粘貼手動代碼,請將鏈接留作評論。否則,請編輯你的答案以適應這個確切的問題。這是一個多維數組。 – mickmackusa

+0

您是否嘗試在手機上編輯代碼? –

+0

此代碼不能提供預期的結果。發佈前您沒有測試過。如果您要提供答案,請完成這項工作。否則,刪除你的答案,繼續前進。 – mickmackusa