如何从PHP中的多维数组中找到最近的数组?

时间:2015-09-24 11:09:20

标签: php

例如:

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];

现在如何查找多维数组 multiArray arrayFindNear 最接近的

回答[最近应该]:multiArray ['two']。

1 个答案:

答案 0 :(得分:0)

尝试类似:

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];

这只是一个想法,代码未经测试......