2

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!

2
  • "if its the same value keep the first array" - then 6005, 6004, 200 should be in result too. Commented Dec 12, 2019 at 17:30
  • I don't understand what you're asking for. How does the "similarity" value" correlate to the two ID values? Commented Dec 12, 2019 at 19:13

1 Answer 1

1

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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.