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

时间:2012-02-05 06:05:27

标签: php arrays swap

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

阵 (     [0] =>排列         (             [city] =>排列                 (                     [0] =>瑞德特                     [1] =>居尔皮普                 )

        [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 = count($ 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);

        }
    }


}

获取所有键的索引,取第一个索引并使用交换将其与其他值进行比较..但它不起作用。有人有一个修复请。谢谢你

1 个答案:

答案 0 :(得分:0)

如果我正确地理解了这一点,你不应该设置$ current = $ next,除非它在if语句中,并且它看起来你还有一个额外的}。我也相信你想改变你的&gt;到&lt;在你的if语句中。这样它就会告诉$ next是否是两者中的较小者。

试试这个:

for($loop=1;$loop<$total;$loop++){

    $next = $array[$loop]['distance'];

    if ($next<$current){
        $current = $next;
        print_r($current);

    }
}

希望它可以帮助你!