从具有较低值的数组中删除重复值
Removes duplicate values from an array with lower value
如何删除关键日期的重复值和具有较低值的关键值?
示例数组:
Array(
[0] => Array
(
[date] => 6.9.
[value] => 0
)
[1] => Array
(
[date] => 6.9.
[value] => 5
))
输出应该是这样的:
Array(
[1] => Array
(
[date] => 6.9.
[value] => 5
))
我认为这会奏效:)
$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'];
}
);
$array = new array(); //your data here
您应该创建一个函数来构建您想要的唯一数组
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;
}
那么你只需要调用函数
max_array_unique($array);
如何删除关键日期的重复值和具有较低值的关键值?
示例数组:
Array(
[0] => Array
(
[date] => 6.9.
[value] => 0
)
[1] => Array
(
[date] => 6.9.
[value] => 5
))
输出应该是这样的:
Array(
[1] => Array
(
[date] => 6.9.
[value] => 5
))
我认为这会奏效:)
$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'];
}
);
$array = new array(); //your data here
您应该创建一个函数来构建您想要的唯一数组
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;
}
那么你只需要调用函数
max_array_unique($array);