RichardMiracles
RichardMiracles

Reputation: 2152

Order a array by date in Laravel

I want to order an array with customer comments by the field date. From the most current date to the oldest.

$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"
]
....

I want to get this result:

$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"
  ]

How can I do this within my Laravel controller or with PHP?

EDIT: I'm trying with usort but I get it wrong

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']) ;
    }

This return me this error:

usort() expects parameter 2 to be a valid callback, function 'compare' not found or invalid function name

Upvotes: 0

Views: 2010

Answers (2)

Sehdev
Sehdev

Reputation: 5662

In Laravel you can do it like:

$array = collect($testimonials)->sortBy('date')->reverse()->toArray();

And in PHP you can use usort to achieve the same

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');

PHP -> usort

Upvotes: 0

nice_dev
nice_dev

Reputation: 17805

Assuming $testimonials is a collection object, you can make use of sortByDesc() to sort by dates in decreasing order.

<?php 

$testimonials = $testimonials->sortByDesc(function($a){
    return DateTime::createFromFormat('d/m/Y',$a['date']);
});

dd($testimonials);

Upvotes: 1

Related Questions