3v4l.org

run code in 300+ PHP versions simultaneously
<?php $arr = [ [ '5' => [ 'BG' => 50, 'CH' => 60, 'LG' => 50, 'MT' => 40, 'MO' => 80, 'PH' => 60, 'GE' => null, ], ], [ '6' => [ 'BG' => 90, 'CH' => 60, 'LG' => 60, 'MT' => 50, 'MO' => null, 'PH' => 50, 'GE' => null, ], ], [ '7' => [ 'BG' => 80, 'CH' => 55, 'LG' => 65, 'MT' => 50, 'MO' => null, 'PH' => 50, 'GE' => 55, ], ], ]; $keys = array_flip(['BG', 'MT', 'GE']); // best of two keys $Ckeys = array_flip(['CH', 'PH', 'MO', 'LG']); // compulsory keys foreach ($arr as $key => $value) { // use to pass parameters to reduce function during call $temp[key($value)] = array_reduce($value, function (&$result, $a) use ($keys, $Ckeys) { // if mo empty then best of two else best of one $bestHowMany = (!empty($a['MO']) ? 1 : 2); // fetching best of keys from $keys $t = array_intersect_key($a, $keys); // reverse sort and maintains keys arsort($t); // fetch top $bestHowMany Values $largest2 = array_slice($t, 0, $bestHowMany); // fetch compulsory values from CKeys $t1 = array_intersect_key($a, $Ckeys); // sum by merging compulsory and best of $bestHowMany values return array_sum(array_merge($t1, $largest2)); }); } print_r($temp);

preferences:
27.47 ms | 413 KiB | 5 Q