vendredi 29 décembre 2017

Laravel merge multiple collections and sort by corresponding datetime field

I have multiple collections merging into one, then sorting that one by datetime to ultimately create a timeline between the collections.

Heres the catch, the datetime columns to sort are different names.

Is there anything I can do to make this cleaner - possibly attach the foreach loop with the ->merge? Looks ugly with the foreach loop. note: code below works but I feel it's a lazy way out and might be slow with more items in the collection.

// Create timeline, sortby creation datetimes.
$TimelineItems = collect();
$AppointmentTemps = collect($Appointments);
$SalesResultTemps = $lead->SalesResult;

$TimelineItems = $AppointmentTemps->merge($SalesResultTemps);
foreach ($TimelineItems as $key => $TimelineItem) {
    if(!empty($TimelineItem->appointment_created)) {
        $TimelineItems[$key]->created_at = $TimelineItem->appointment_created;
    }
    if(!empty($TimelineItem->salesresult_created_timestamp)) {
        $TimelineItems[$key]->created_at = $TimelineItem->salesresult_created_timestamp;
    }
}
$TimelineItems = $TimelineItems->sortByDesc('created_at');
dd($TimelineItems);



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2CnZsgg
via IFTTT

Aucun commentaire:

Enregistrer un commentaire