Reputation: 5355
I am using PHP 7.1.33
.
I am the following array:
[6114, 6128, 26.89] // --> [ID_1, ID_2, similarity_value]
I would like to filter if ID_1
and ID_2
are similar and pick the array with the higher similarity value
(if its the same value keep the first array), such as:
[6114, 6128, 26.89] // keep this value
[6128, 6114, 25.60]
I am struggeling with the comparing part of the IDs. I tried the following:
<?php
$valueArr = [
[6114, 6128, 26.89],
[6128, 6114, 25.60],
[1000, 2000, 35.33],
[2000, 1000, 55.55],
[6000, 6001, 35.98],
[6005, 6004, 200],
[6004, 6005, 200]
];
/**
* @param array $valueArr
* @return array
*/
function removeDoublesAndKeepHigh($valueArr)
{
$resArr = array();
foreach ($valueArr as $v) {
foreach ($valueArr as $y) {
if ($v[0] === $y[1]) {
if ($y[1] === $v[1]) {
array_push($resArr, $v);
}
}
}
}
return $resArr;
}
$resArr = removeDoublesAndKeepHigh($valueArr);
print_r($resArr);
/*
Wanted Result:
$resArr = [[6114, 6128, 26.89], [2000, 1000, 55.55], [6000, 6001, 35.98]];
*/
Any suggestions what I am doing wrong? Should I add another for-loop
?
Appreciate your replies!
Upvotes: 2
Views: 62
Reputation: 54841
My version with taking "if its the same value keep the first array" into consideration (fiddle here) is:
$valueArr = [
[6114, 6128, 26.89],
[6128, 6114, 25.60],
[1000, 2000, 35.33],
[2000, 1000, 55.55],
[6000, 6001, 35.98],
[6005, 6004, 200],
[6004, 6005, 200]
];
$newData = [];
foreach ($valueArr as $value) {
$key = $value[0] < $value[1]
? $value[0] . '-' . $value[1]
: $value[1] . '-' . $value[0];
if (empty($newData[$key]) || $newData[$key][2] < $value[2]) {
$newData[$key] = $value;
}
}
print_r(array_values($newData));
Upvotes: 1