【问题标题】:Find Shortest distance from an array of arrays using php使用php从数组数组中查找最短距离
【发布时间】:2012-02-05 06:05:26
【问题描述】:

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

数组 ( [0] => 数组 ( [城市] => 数组 ( [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]['距离'];

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

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

    if ($next>$current){

        print_r($current);

        }
    }


}

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

【问题讨论】:

    标签: php arrays swap


    【解决方案1】:

    如果我理解正确,你不应该设置 $current = $next 除非它在 ​​if 语句中,而且你似乎还有一个额外的 } 在那里。我也相信您想在 if 语句中将 > 更改为

    试试这个:

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

    希望对你有所帮助!

    【讨论】:

    • 我明白你的意思,但我希望这个条件显示最短距离
    • 在我发布的 for 循环上方添加此代码:$current = $array[0]['distance'];我几乎可以肯定这会产生你想要的。这会将数组中的第一项设置为最接近的。然后 for 循环将检查下一项是否小于当前项 ($next
    • 是的,但我想要它打印所有值的最后一个最小值
    • 将 print_r($current) 从 if 语句内部移动到 for 循环之后
    猜你喜欢
    • 2021-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-09
    • 1970-01-01
    • 2011-04-30
    • 1970-01-01
    相关资源
    最近更新 更多