希望有人能帮助我从这个示例脚本中确定如何初始化这个变量($value),我从PHP中复制了Vikram Vaswani的初学者指南。
我在php.ini中打开了display_erors值,它在浏览器中返回这个错误。
注意:未定义的变量:城市位于C:''BitNami''wordpress-3.6-0''apache2''htdocs''associative-array.php的第23行
警告:第23行C:''BitNami''wordpress-3.6-0''apache2''htdocs''associative-array.php中为foreach()提供的参数无效
这是我从这本书第94页复制的代码
<?php
// define array
$citites = array(
"United Kingdom" => "London",
"United States" => "Washington DC",
"France" => "Paris",
"India" => "Delhi"
);
// Iterate over the associative array
// and print each value
// this example as supplied in the book
// returns uninitialized error for either $key or $value on line 20
foreach ($cities as $key => $value) {
echo "$value is in $key. 'r'n";
}
?>
同样在同一章中,复制了另一个例子,因为"数组迭代器"只是无限期地挂在浏览器中。到目前为止,书中的所有例子似乎都很完美。
这是从书中为数组迭代器示例复制的代码。任何人都知道为什么这会无限期地挂起,并且不向浏览器显示输出。非常感谢你的帮助。
<?php
// define associative array (hash)
$cities = array(
"United States" => "Washington",
"United Kingdom" => "London",
"France" => "Paris",
"Spain" => "Madrid",
"Italy" => "Rome"
);
// Create an array itterator object
$iterator = new ArrayIterator($cities);
// rewind to beginning of array
$iterator->rewind();
// iterate over the array
// print each value
while ($iterator->valid()) {
print $iterator->current() . " is in " . $iterator->key() . ". 'r'n";
$iterator->next;
}
?>
在最后一行附近将$iterator->next
更改为$iterator->next()
。
$iterator->next
不起作用,因为PHP假设您正在访问字段而不是调用方法。调用方法需要方括号()
。
我认为$iterator->next
是指调用一个函数,而不是试图访问ArrayIterator
($iterator
)类的变量,名为next
。
为了调用函数,您需要在函数名(即function_name()
)后添加一组括号,必要时可以添加或不添加一系列参数。
因此,应该使用$iterator->next()
而不是$iterator->next
。
在第一个例子中,错误在这一行:
$citites = array(
你在这里拼错了"cities",这打破了foreach循环。
在第二个示例中,只需将$iterator->next
更改为$iterator->next()
。这将告诉PHP它是一个方法而不是字段,从而允许正确地调用它。
您正试图访问一个方法,所以应该用第一个括号将其关闭。您应该使用$iterator->next()而不是$iterator->next。