id)->orderByRaw('CAST(data->"$.rank" AS UNSIGNED)')->get(); $rankGroupedNominations = $nominations->groupBy(function ($entry) { return $entry->data['rank']; }); $acceptedNominations = collect(); $rankOn = 1; // Collect students to add to the ensemble while ($rankOn <= $ensemble->data['max_nominations'] && $rankGroupedNominations->has($rankOn)) { // If were at or over the target size of the ensemble, stop adding people if ($acceptedNominations->count() >= $ensemble->data['target_size']) { break; } // Add people of the current rank to the ensemble foreach ($rankGroupedNominations[$rankOn] as $nomination) { $acceptedNominations->push($nomination); } $rankOn++; // If we want to round down the ensemble size, quit adding people if hte next rank will exceed the target if ( $rankGroupedNominations->has($rankOn) && $acceptedNominations->count() + $rankGroupedNominations[$rankOn]->count() >= $ensemble->data['target_size'] && $ensemble->data['rounding_direction'] === 'down' ) { break; } } dd($acceptedNominations); } }