使用php查找与数组数组的最短距离


Find Shortest distance from an array of arrays using php

我想比较从数组[0]到数组末尾的距离,并用它的键显示最短距离。

阵列([0]=>数组([city]=>阵列([0]=>赔偿[1] =>Curepipe)

        [distance] => 14.4
    )
[1] => Array
    (
        [city] => Array
            (
                [0] => Array
                    (
                        [0] => Reduit
                        [1] => Ebe
                    )
                [1] => Bees Village
                [2] => Phoen Trunk Rd
                [3] => Riv,Phoenix
                [4] => St l Rd
                [5] => Geoes Guibert St
                [6] => Curepipe
            )
        [distance] => 1.4
    )
[2] => Array
    (
        [city] => Array
            (
                [0] => Array
                    (
                        [0] => Reduit
                        [1] => Riv,Phoenix
                    )
                [1] => St l Rd
                [2] => Geoes Guibert St
                [3] => Curepipe
            )
        [distance] => 3.4
    )
[3] => Array
    (
        [city] => Array
            (
                [0] => Array
                    (
                        [0] => Reduit
                        [1] => Ebene
                    )
                [1] => Belles Village
                [2] => Phoenix Trunk Rd
                [3] => Riverside,Phoenix
                [4] => St Paul Rd
                [5] => Georges Guibert St
                [6] => Curepipe
            )
        [distance] => 22.4
    )

)

我用

$total=计数($array)-1;$current=$array[0]['distance'];

for($loop=1;$loop<$total;$loop++){
    $next = $array[$loop]['distance'];
    $current = $next;
    $current = $current;
    if ($next>$current){
        print_r($current);
        }
    }

}

要获得所有键的索引,请获取第一个索引,并使用swaping将其与其他值进行比较。。但它不起作用。请有人帮忙。感谢

如果我正确理解这一点,您不应该设置$current=$next,除非它在If语句中,而且它似乎还有一个额外的}。我还认为您希望将>更改为<在if语句中。这样它就能判断next美元是否是两者中较小的一个。

试试这个:

for($loop=1;$loop<$total;$loop++){
    $next = $array[$loop]['distance'];
    if ($next<$current){
        $current = $next;
        print_r($current);
    }
}

希望它能帮助你!