"as $key => 之间的区别$值"和“作为 $value"在 PHP foreach 中

2021-12-26 00:00:00 arrays foreach php

我有一个数据库调用,我想弄清楚 $key =>$valueforeach 循环中执行.

I have a database call and I'm trying to figure out what the $key => $value does in a foreach loop.

我问的原因是因为这两个代码输出相同的东西,所以我试图理解为什么它是这样写的.代码如下:

The reason I ask is because both these codes output the same thing, so I'm trying to understand why it's written this way. Here's the code:

1)在foreach中使用$key =>$value

1)In foreach use $key => $value

foreach($featured as $key => $value){
  echo $value['name'];
}

这个输出与:

2)在 foreach 中只使用 $value

2)In foreach use only $value

foreach($featured as $value) {
  echo $value['name'];
}

所以我的问题是,$key => 和有什么区别?$value$valueforeach 循环中.如果这有所不同,数组是多维的,我只想知道为什么在 foreach 循环中将 $key 传递给 $value.

So my question is, what is the difference between $key => $value or just $value in the foreach loop. The array is multidimensional if that makes a difference, I just want to know why to pass $key to $value in the foreach loop.

推荐答案

好吧,$key =>foreach 循环中的 $value 指的是关联数组中的键值对,其中键作为索引来确定值,而不是像 0,1,2,... 这样的数字在 PHP 中,关联数组看起来像这样:

Well, the $key => $value in the foreach loop refers to the key-value pairs in associative arrays, where the key serves as the index to determine the value instead of a number like 0,1,2,... In PHP, associative arrays look like this:

$featured = array('key1' => 'value1', 'key2' => 'value2', etc.);

在 PHP 代码中:$featured 是循环遍历的关联数组,as $key =>$value 表示每次循环运行并从数组中选择一个键值对时,它将键存储在本地 $key 变量中以在循环块内使用和值在本地 $value 变量中.因此,对于我们上面的示例数组,foreach 循环将到达第一个键值对,如果您将 指定为 $key =>;$value,它会将 'key1' 存储在 $key 变量中,将 'value1' 存储在 $value 中 变量.

In the PHP code: $featured is the associative array being looped through, and as $key => $value means that each time the loop runs and selects a key-value pair from the array, it stores the key in the local $key variable to use inside the loop block and the value in the local $value variable. So for our example array above, the foreach loop would reach the first key-value pair, and if you specified as $key => $value, it would store 'key1' in the $key variable and 'value1' in the $value variable.

由于您不在循环块中使用 $key 变量,因此添加或删除它不会改变循环的输出,但最好包含键值对表明它是一个关联数组.

Since you don't use the $key variable inside your loop block, adding it or removing it doesn't change the output of the loop, but it's best to include the key-value pair to show that it's an associative array.

还要注意 as $key =>$value 指定是任意的.您可以将其替换为 as $foo =>$bar 并且只要您将循环块内的变量引用更改为新变量 $foo$bar,它就可以正常工作.但是让它们成为 $key$value 有助于跟踪它们的含义.

Also note that the as $key => $value designation is arbitrary. You could replace that with as $foo => $bar and it would work fine as long as you changed the variable references inside the loop block to the new variables, $foo and $bar. But making them $key and $value helps to keep track of what they mean.

相关文章