-1

我遇到了这段代码,foreach($vars as $a=>$var){ // some process here}我想知道使用时有什么区别foreach($vars as $var){ // some process here}?谢谢。

4

4 回答 4

2

运算符=>表示键和值之间的关系。你可以想象关键指向=>价值。

编辑:

foreach可以通过两种方式使用:

1.迭代值:

每次循环时,变量都会设置为数组中的下一个值。

例如:

$fruitColours = array(
    "Banana" => "Yellow",
    "Apple"  => "Green",
    "Plum"   => "Purple",
);

foreach ($fruitColours as $colour)
{
    echo "$colour<br/>\n";
}

?>

上面会显示:

Yellow
Green
Purple

仅显示数组的值。

2.迭代键和值

每次循环,变量都被设置为下一个键值对。

例如:

$fruitColours = array(
    "Banana" => "Yellow",
    "Apple"  => "Green",
    "Plum"   => "Purple",
);

foreach ($fruitColours as $fruit => $colour)
{
    echo "$fruit is $colour<br/>\n";
}

?>

上面会显示:

Banana is Yellow
Apple is Green
Plum is Purple

检查php foreach 文档以获取更多参考

于 2012-09-10T17:17:07.940 回答
2
$vars = array(
  'key1'=>'something',
  'key2'=>'test',
);

foreach($vars as $key=>$value){
  echo "$key:$value" . PHP_EOL;
}

将输出:

key1:something
key2:test
于 2012-09-10T17:17:16.453 回答
1

foreach($vars as $a=>$var){ // some process here} 遍历一个数组($vars在这种情况下)。在每次迭代中,$a都归属于实际数组项的键和$var相应的值。

foreach($vars as $var){ // some process here}和上面一样,但是用这个,只返回每个数组项的值。不返回键值。

查看php 手册中的这篇文章以获取更多信息。

于 2012-09-10T17:21:38.907 回答
1

不同的是,foreach($vars as $var){ // some process here}你只得到价值,而foreach($vars as $a=>$var){ // some process here}你也得到它的钥匙。

    $data = array('NAME' => 'Tom', 'AGE' => 20);

foreach($data as $var){
    echo $var . "\n";
}
echo "\n";
foreach($data as $key => $var){
        echo $key .': '. $var . "\n";
}

将输出

Tom
20

NAME: Tom
AGE: 20
于 2012-09-10T17:23:42.480 回答