I have this array with other 16 arrays
array:16 [▼ 0 => array:6 [▼ "id" => 1867 "meta_date" => IlluminateSupportCarbon @1564536945 {#4600 ▼ date: 2019-07-31 01:35:45.0 UTC (+00:00) } "title" => "" "summary" => """ 1 => array:6 [▼ "id" => 1868 "meta_date" => IlluminateSupportCarbon @1524215895 {#4465 ▼ date: 2018-04-20 09:18:15.0 UTC (+00:00) } "meta_type" => "" "title" => "" "summary" => """
and so on…
I want to sort the main array by date specified in “meta_date” field included on each “child” array, the sort can be $sort= "asc"
or $sort= "desc"
and
I want to take a dynamic limit for the main array, for example if $limit=10
take the first 10 arrays sorted by date selected
currently, I’m using PHP 7.3 and laravel 8
Advertisement
Answer
Laravel’s collections come with everything you need:
collect($arr)->{$sort === 'desc' ? 'sortByDesc' : 'sortBy'}('meta_date')->take($limit)->values()->all();