在php中查找多维数组中两个值之间的距离

时间:2015-11-09 17:22:46

标签: php multidimensional-array

我是php的新手,想找出问题的答案

          Find two closest objects by distance.

          @param array $objects The list of objects with the name and  coordinates.
          @return array The closest objects names.

          An example:
              php> $obj1 = ['name' => 'a', 'x' => 1, 'y' => 1];
              php> $obj2 = ['name' => 'b', 'x' => 1, 'y' => 2];
              php> $obj3 = ['name' => 'c', 'x' => 10, 'y' => 10];
              php> = findClosest([$obj1, $obj2, $obj3])
              array(
                0 => "a",
                1 => "b",
              )



function findClosest(array $objects)
    {
        // ...
    }

我试过这个:

<?php
function findClosest(array $objects) {
    function cmp($a, $b) {
        if( ($a["x"] < $b["x"])&&($a["y"] < $b["y"]) ) return -1; //echo "</br>";
    }
    echo usort($objects, "cmp");
    $arrlength=count($objects);
    for($x=0;$x<$arrlength;$x++) {
        print_r($objects[$x]) ; //echo "<br>";
    }
}
findClosest($objects);
?>

2 个答案:

答案 0 :(得分:0)

请注意,这将适用于为findClosest finction提供的任意数量的参数/点($ obj4,$ obj5 ......)

function cmp($a, $b) {
    return $a['distance'] - $b['distance'];
}

function findClosest(array $obj)
{
    $i=0;
    foreach($obj as $key1 => $o1){
      foreach($obj as $key2 => $o2){
        if($key1 !== $key2 && $key1 < $key2){
            $distance[$i]['distance'] = sqrt(pow($o2['x'] - $o1['x'], 2) + pow(o2['y'] - $o1['y'], 2));
            $distance[$i]['first'] = $o1['name'];
            $distance[$i]['second'] = $o2['name'];
            $i++;
        }
      }
    }
    usort($distance, "cmp");
    $closer = array ($distance[0]['first'], $distance[0]['second']);
    return $closer;
}

$obj1 = ['name' => 'a', 'x' => 1, 'y' => 1];
$obj2 = ['name' => 'b', 'x' => 1, 'y' => 2];
$obj3 = ['name' => 'c', 'x' => 10, 'y' => 10];

findClosest([$obj1, $obj2, $obj3]);

答案 1 :(得分:0)

您必须迭代每个可能的组合并计算这些组之间的距离。

function findClosest(array $objects) {
    if (count($objects) < 2) return false;

    // distance between $a, and $b
    $fd = function($a, $b) {return sqrt(pow($a['x'] - $b['x'], 2) + pow($a['y'] - $b['y'], 2)); };
    $init = [
        'd' => $fd($objects[0], $objects[1]),
        'a' => $objects[0],
        'b' => $objects[1]];

    // iterate over each combination
    for ($i = 0; $i < count($objects) - 1; $i++) {
        for ($j = $i + 1; $j < count($objects); $j++) {
            $distance = $fd($objects[$i], $objects[$j]);
            if ($distance < $init['d']) {
                $init['d'] = $distance;
                $init['a'] = $objects[$i];
                $init['b'] = $objects[$j];
            }
        }
    }

    // return the smallest distance
    return [$init['a'], $init['b']];
}