Ad

Order A Array By Date In Laravel

- 1 answer

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
Ad

Answer

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);
Ad
source: stackoverflow.com
Ad