Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel sort an array by date

hello friends I have an array that looks like this:

array:3 [▼
  0 => array:6 [▼
    "date" => "2016-05-31 15:08:33"
    0 => "31 May 16"
    1 => "aze"
    2 => "2"
    3 => "hi"
    4 => "487841464704194.jpg"
  ]
  1 => array:6 [▼
    "date" => "2016-05-31 15:26:09"
    0 => "31 May 16"
    1 => "aze"
    2 => "2"
    3 => "hey"
    4 => "487841464704194.jpg"
  ]
  2 => array:6 [▼
    "date" => "2016-06-01 11:33:06"
    0 => "01 Jun 16"
    1 => "aze"
    2 => "2"
    3 => "Dm me please"
    4 => "487841464704194.jpg"
  ]
]

My goal is to sort it by the date. So from new to old.

If tried this:

$comarrSorted = $comarr->sortByDesc('date');
dd($comarrSorted);

But I get this nasty error:

Call to a member function sortByDesc() on array

Anyone can help me out? I guess the error is caused because it's a collection function? Is it not possible to sort my array with this function?

Many Thanks in advance!

like image 825
Cruzito Avatar asked Jun 01 '16 11:06

Cruzito


3 Answers

You can convert to a collection, call the sortBy() and the convert back to an array all on one line.

$sortedArr = collect($array)->sortBy('date')->all();
like image 191
Chukwuemeka Inya Avatar answered Oct 13 '22 00:10

Chukwuemeka Inya


you have to create your own function

array_sort_by_column($array, 'date');


function array_sort_by_column(&$array, $column, $direction = SORT_ASC) {
    $reference_array = array();

    foreach($array as $key => $row) {
        $reference_array[$key] = $row[$column];
    }

    array_multisort($reference_array, $direction, $array);
}
like image 21
Hiren Makwana Avatar answered Oct 12 '22 23:10

Hiren Makwana


You can use this solution to get the result:

collect($yourArray)->sortBy('Key')->values();
like image 20
pankaj kumar Avatar answered Oct 13 '22 01:10

pankaj kumar