Look at various collection methods, you need max value, so use methods together.
You could always sort desc and top value would be answer.
I have an array of Greenscreen List Translator scores from worst to best like so:
$hazards = [
'BM-1' => 8,
'LT-1' => 7,
'LT-P1' => 6,
'LT-UNK' => 5,
'BM-2' => 4,
'BM-3' => 3,
'BM-4' => 2,
'BM-U' => 1,
'NoGS' => 0,
'Not Screened' => 0,
];
I have a collection of models and I need to filter the collection down to the model with the highest score.
I have this and it does return a model, but it's not consistently the correct one.
$worst = $items->filter(function($item) use($hazards) {
return $hazards[$item->field];
})->max();
Maybe I'm reaching for the wrong collection method?
Thanks
Ok so here's a version with the map method.
$score = $items->map(function($item) use($hazards) {
return $hazards[$item->field];
})->max();
$ha = array_flip($hazards);
$worst = $ha[$score];
Not exactly elegant but it always returns the correct item from the collection.
Thanks @jlrdw for trying to help out, much appreciated.
Please or to participate in this conversation.