php 等号 箭头,关于数组:PHP在foreach循环中等于箭头运算符

本问题已经有最佳答案,请猛点这里访问。

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来获取成员变量。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值