I'm trying to figure out a simple way to remove/unset duplicate array values based off a higher secondary value in the array in php.
Here's an simple example of the original array.
$ar = array(
array('pid'=>'544', 'discount'=>'26.00','promo_id'=>'9807'),
array('pid'=>'544', 'discount'=>'15.00','promo_id'=>'9821'),
array('pid'=>'544', 'discount'=>'21.00','promo_id'=>'9811'),
array('pid'=>'2965','discount'=>'25.00','promo_id'=>'9810'),
array('pid'=>'2965','discount'=>'30.50','promo_id'=>'9809'),
array('pid'=>'1866','discount'=>'30.00','promo_id'=>'9810'),
array('pid'=>'1866','discount'=>'25.50','promo_id'=>'9809')
);
This would be the NEW array that I would like to get.
$ar = array(
array('pid'=>'544', 'discount'=>'26.00','promo_id'=>'9807'),
array('pid'=>'2965','discount'=>'30.50','promo_id'=>'9809'),
array('pid'=>'1866','discount'=>'30.00','promo_id'=>'9810'),
);
These would be the keys that have been removed.
//array('pid'=>'1866','discount'=>'25.50','promo_id'=>'9809') Removed!
//array('pid'=>'544', 'discount'=>'21.00','promo_id'=>'9811'), Removed!
//array('pid'=>'544', 'discount'=>'15.00','promo_id'=>'9821'), Removed!
//array('pid'=>'2965','discount'=>'25.00','promo_id'=>'9810'), Removed!
I would like to remove any duplicate values of the 'pid' by KEEPING the highest value of the 'discount'.
The array may have more than two keys that have the same 'pid' but they would never have the same 'pid' and 'promo_id'.
Hopefully there is an easy solution for this.
EDIT:
Here what I've been trying.
foreach($ar as $tkey => $v) {
$tPID = $v['pid'];
$tDISC = $v['discount'];
if ($tPID) {
$key = array_search($tPID, array_column($ar, 'pid'));
$aPID = $ar[$key]['pid'];
$aTPRD = $ar[$key]['discount'];
if ($aTPRD < $tDISC) {
echo '(UN:'.$tkey.')'; unset($ar[$tkey]);
}else
if ($aTPRD > $tDISC) {
echo '(UN:'.$key.')'; unset($ar[$key]);
}else{echo 'else'; }
}
}