简体   繁体   中英

How To Find Nearest array From Multidimensional Array in php?

For Example :

multiArray = {
  'one':  [37, 50, 52, 54],
  'two':  [46, 48, 50, 52],
  'three':[37, 38, 39, 40],
  'four': [37, 38, 39, 40],
  'five': [46, 48, 50, 54],
  'six':  [46, 50, 52, 54],
}   

arrayFindNear = [46, 48, 49, 51];

Now How To Find Which is the nearest one for arrayFindNear in multidimentional Array multiArray ???

Answer[Nearest Should Be] : multiArray['two'].

Try something like:

function arrayDistance($array1, $array2) {
    $distance = 0;
    for(i = 0; i < size($array1); i++) {
        $distance += $array1[i] - $array2[i];
    }
    return abs($distance);
}

$nearestArrayKey = null;
$nearestArrayDistance = null;

foreach($multiArray as $key => $value) {
    $distance = arrayDistance($arrayFindNear, $value);
    if($distance < $nearestArrayDistance || $nearestArrayDistance == null) {
        $nearestArrayKey = $key;
        $nearestArrayDistance = $distance;
    }
}

$result = null;
if($nearestArrayKey != null)
    $result = $multiArray[$nearestArrayKey];

It's just an idea, the code is untested...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM