本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
What does $k => $v in foreach($ex as $k=>$v) mean?
我试图了解这意味着什么:
foreach($this->domains as $domain=>$users) {
// some code...
}
我知道$this->domains是foreach将会索引的数组。 但是as $domain=>$users是什么意思? 我只看到数组中使用=>运算符来设置(键,值)对。 该类有一个名为$domain的成员,但我认为可以作为$this->domain访问。
=>运算符指定关联。因此,假设$this->domains是数组,则$domain将是键,而$users将是值。
$domains['example.com'] = 'user1';
$domains['fred.com'] = 'user2';
foreach ($domains as $domain => $user) {
echo '$domain, $user
';
}
输出:
example.com, user1
fred.com, user2
(在您的示例中,$users可能是用户数组);
这样想:
foreach($this->domains as $key=>$value) {
它将逐步遍历$this->domains作为键/值对返回的关联数组中的每个元素。键将在$domain中,值将在$users中。
为了帮助您理解,可以将以下行放在您的foreach循环中:
echo $domain," =>", $users;
阅读foreach
foreach (array_expression as $value)
statement
foreach (array_expression as $key => $value)
statement
The first form loops over the array given by array_expression. On each
loop, the value of the current element is assigned to $value and the
internal array pointer is advanced by one (so on the next loop, you'll
be looking at the next element).
The second form does the same thing, except that the current element's
key will be assigned to the variable $key on each loop.
$domain这里是一个局部变量,包含数组中当前项的键。那就是你的数组是:
$ages = array("dad" => 31,"mom" => 35,"son" => 2);
然后
foreach($ages as $name=>$age)
{
// prints dad is 32 years old, mom is 35 years old, etc
echo"$name is $age years old"
}
在循环主体中,引用$name将引用当前键,即"爸爸","妈妈"或"儿子"。并且$age指的是我们在当前密钥上存储的年龄。
assume that would be accessed as $this->domain.
没错,只是$domain是此处的局部变量。您需要$this->domain来获取成员变量。