Created
March 11, 2016 18:09
-
-
Save tpavlek/216ecc96a6b2b3064ab9 to your computer and use it in GitHub Desktop.
Rolling up Data in a collection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
The purpose of this is we pull a SQL query, and then by grouping together we will get sets of two and we want to see if the most | |
recent item in the set has increased or decreased relative to the other items. The final form of the result needs to take the form | |
[ | |
'decreased' => $count, | |
'no-change' => $count, | |
'increased' => $count, | |
] | |
What I have is below. I especially don't like the last three lines where I'm forced to move out of the functional style and use | |
null coalescing three times. I think it could look better. | |
$rollup = collect($query->get()) | |
->groupBy(function ($results_data) { | |
// The query restricts two only two days, so this will return pairings of a engine-keyword-location | |
// that we can compare for ranking changes. | |
return "$results_data->engine|$results_data->keyword_id|$results_data->location_id"; | |
}) | |
->map(function (Collection $collection) { | |
$collection = $collection->sortByDesc('created_at_date'); | |
if ($collection->count() > 2) { | |
// There was an error with the query, we're missing a dispatch. Assume the missing dispatch is unranked | |
return (int)$collection->first()->rank <=> 0; | |
} | |
return (int)$collection->first()->rank <=> (int)$collection->last()->rank; | |
})->groupBy(function ($item, $key) { | |
return $item; | |
})->map(function (Collection $groups) { | |
return $groups->count(); | |
}); | |
$rollup['decreased'] = $rollup->get(-1) ?? 0; | |
$rollup['no-change'] = $rollup->get(0) ?? 0; | |
$rollup['increased'] = $rollup->get(1) ?? 0; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment