0

How can I remove duplicate values of key date and key value with lower value?

Example array:

Array(

[0] => Array
(
    [date] => 6.9.
    [value] => 0
)

[1] => Array
(
    [date] => 6.9.
    [value] => 5
))

and the output should be like this:

Array(

[1] => Array
(
    [date] => 6.9.
    [value] => 5
))
  • possible duplicate of [How to remove duplicate values from an array in PHP](http://stackoverflow.com/questions/307650/how-to-remove-duplicate-values-from-an-array-in-php) – syck Sep 08 '15 at 15:41

2 Answers2

0

I think this will work :)

$array = [...];
$max_values = [];
foreach($array as $row) {
    if(!isset($max_values[$row['date']])) {
        $max_values[$row['date']] = $row['value'];
    }
    if($max_values[$row['date']] < $row['value']) {
        $max_values[$row['date']] = $row['value'];
    }
}

$filtered_array = array_filter($array, function($value) use ($max_values) {
        return $max_values[$value['date']] <= $value['value'];
    }
);
0
$array = new array(); //your data here

You should create a function to build the unique array you want

function max_array_unique($array) {
    $hash = new array();
    foreach($array as $row) {
         if (array_key_exist($hash, $row['date']) {
            if ($row['date'] > $hash[row['date']]) {
                $hash[$row['date']] = $row['value'];
            }
         } else {
             $hash[$row['date']] = $row['value'];
         }
    }
    $result = new array();
    foreach($hash as $key => $value) {
        $result[] = array(
            'date' => $key,
            'value' => $value,
        );
    }
return $result;
}

Then you just have to call the function

max_array_unique($array);
Unex
  • 1,747
  • 13
  • 17