I'm trying to sort an array prioritizing the closest macros value to the optimal values, i.e the element best matching the criteria is id of 200 (but is sorted), looks like all the "points" goes to the prev
element instead.
function sorter(array $array, $optimal, $minMax){
usort($array, function($prev, $curr) use($optimal, $minMax){
$points = ['prev' => 0, 'curr' => 0];
foreach($curr['macros'] as $macro => $value){
if($value > $minMax[$macro]["minimum"] && $value <= $optimal[$macro]){
if($macro === "protein"){
$points['curr'] += 2;
}
if($macro === "carb" && $value < $prev["macros"][$macro]){
$points['curr'] += 1;
}
++$points['curr'];
} else {
++$points['prev'];
}
}
if($points['prev'] === $points['curr']) return 0;
return $points['prev'] < $points['curr'] ? -1 : 1;
});
return $array;
}
The protein
has a higher priority, with carbs
coming second.
http://sandbox.onlinephpfunctions.com/code/77fc35f2fb0b60de9271f7e934a5a8a4aa3b25a3