打印PHP二维数组

3
我有以下代码:
<!DOCTYPE html>
<html >
<head>
    <title>Distance</title>
</head>

<body>
    <?php

        $distance = array(
            array(0, 200, 57, 223),
            array(200, 0, 150, 5),
            array(57, 150, 0, 177),
            array(57, 150, 0, 177),
            array(223, 5, 177, 0)
        );

        $cityA = filter_input(INPUT_POST, "cityA");
        $cityB = filter_input(INPUT_POST, "cityB");
        $result = $distance[$cityA][$cityB];

        print "<p> The distance between the 2 cities is $result</p>";

    ?>
</body>
</html>

对于代码:

 print "<p> The distance between the 2 cities is $result</p>";

结果为:

这是结果。

The distance between the 2 cities is 177

但是如果我把它改成:

 print "<p> The distance between the 2 cities is $distance[$cityA][$cityB]</p>";

结果变成了:
The distance between the 2 cities is Array[0]

有人能解释一下为什么我直接打印$distance[$cityA][$cityB]时它不被解释为一个二维数组吗?


$cityAе’Ң$cityBзҡ„еҖјжҳҜд»Җд№Ҳпјҹ - Martin
你需要将 $distance 数组的键和值都改变,因为我不知道你的脚本如何知道哪个城市有什么坐标。 - David
@David:它确实有键,这就是数组的工作原理。它们是数字的。从0到4,以及从0到3。 - gen_Eric
1个回答

4

尝试用花括号将其包裹起来。

print "<p> The distance between the 2 cities is {$distance[$cityA][$cityB]}</p>";

谢谢你的解决方案,Rocket。但是我的方法为什么不起作用?PHP应该理解$var,并且当我将其放在打印语句中时应该能够识别它。 - fall
@fall:看起来PHP在第一个]处停止解析,第二个[$cityB]没有被读取为变量的一部分。 - gen_Eric

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接