Sorting config variable based on date in laravel

I have a config variable that uses a foreach loop to print all objects. Is there a way to sort what prints based on date? Here is my code to print the object. I want to sort it based on$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

:

'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"
      ],
],

      

+3


source to share


2 answers


You should be able to use Laravel collections to do this fairly easily. Complete the call config()

when called collect()

, and then use the method sortBy()

in the collection to sort the records by the value strtotime()

of the date key. Use this method sortByDesc()

if you want to sort in a different way.

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

      



The documentation is here .

+1


source


You can use usort

PHP function .

The following code is taken from the PHP manual and modified to reflect your needs.



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


source







All Articles