我真的在努力做这项工作,我看过导游,但我似乎无法看到我和他们之间的区别,除了阵列的布局。
<?php
$country = array('England' => "London", 'Scotland' => "Edinburgh", 'France' => "Paris");
foreach ($capitals as $country=>$capital) {
echo "The capital of $country is $capital";
}
?>
我想要它做的就是说这个国家及其首都。
错误代码 -
Notice: Undefined variable: capitals in C:\xampp\htdocs\foreach.php on line 4
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\foreach.php on line 4
提前致谢。
答案 0 :(得分:5)
将您的代码更改为:
(我将数组名称从country
更改为capitals
)
<?php
$capitals = array('England' => "London", 'Scotland' => "Edinburgh", 'France' => "Paris");
foreach ($capitals as $country=>$capital) {
echo "The capital of $country is $capital<br />";
}
?>
输出:
The capital of England is London
The capital of Scotland is Edinburgh
The capital of France is Paris
答案 1 :(得分:0)
您正在尝试遍历不存在的数组$capitals
。你必须遍历数组$country
。
foreach ($country as $country=>$capital) {
echo "The capital of $country is $capital";
}