I have an associative array $result
represented as
$result[0]['id']=120
$result[0]['point']=3.4
$result[1]['id']=136
$result[1]['point']=4.5
$result[2]['id']=140
$result[2]['point']=5.6
$result[3]['id']=120
$result[3]['point']=6.7
I want to make this array unique by id
, but on a condition that the the unique array contains element with the higher point
. For the above example I wanted the output to be
$result[0]['id']=136
$result[0]['point']=4.5
$result[1]['id']=140
$result[1]['point']=5.6
$result[2]['id']=120
$result[2]['point']=6.7
I tried the code below it will only make the array unique by id
, but cannot check the condition.
function super_unique($array, $key) {
$temp_array = array();
foreach($array as & $v) {
if (!isset($temp_array[$v[$key]]))
$temp_array[$v[$key]] = & $v;
}
$array = array_values($temp_array);
return $array;
}
Please help thanks in advance
$newarr = array();
foreach($array as $v) {
if (!isset($newarr[$v['id']]) || ($newarr[$v['id']] < $v['point'])) {
$newarr[$v['id']] = $v['point'];
}
}
General tip: Don't use references like you are in the foreach loop. While it's not a concern with this particular code snippet, referenced varaibles in foreach loops can cause very-hard-to-find bugs in code where that particular variable name is re-used later on in later code.
$test = super_unique($result);
var_dump($test);
function super_unique($array){
$newArray = array();
foreach($array as $val){
$id = $val["id"];
$point = $val["point"];
if(!isset($newArray["$id"]) || ($point > $newArray["$id"])){
$newArray["$id"] = $point;
}
}
//asort($newArray); want to sorting by point???
$output = array();
$i = 0;
foreach($newArray as $key => $value){
$output[$i]["id"] = $key;
$output[$i]["point"]=$value;
$i++;
}
return $output;
}