You could do this using usort
on your array of date strings. You would compare them e.g. with strotime($a) <=> strtotime($b)
, or array_reverse(explode('-', $a)) <=> ... $b
on all dates. However, this approach would quickly become a very expensive operation, given the cartesian(?) amount of conversions that would be made when each item is compared, unless the conversions were somehow cached. I wouldn't go down this path here.
In general, it's better to sort your data when the data is still in a more readily comparable format, where at all possible. I don't think you can just usort
Carbon objects though (without some overhead, as above, anyway!), so here's a no-frills solution that performs well.
Assuming the array keys hold no particular meaning for you, you can generate timestamps for keys. You can then scrap all the unshift/push logic, and simply do something like this:
$timestamp = Carbon::parse($value->fecha)->timestamp;
$times[$timestamp] = $value;
This will give you an array (here, $times
) of date strings with timestamp-indexes. (Adapt the variables to fit your case.) Then it's as trivial as applying ksort
($times)
to the resulting array, ie. sorting the array by key. Your date strings will be in chronological order.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…