本文介绍了为$关键=>&QUOT之间的差异; $值"和"为$值"在PHP的foreach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据库调用,我试图找出什么 $键=> $值确实在的foreach 循环。

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

我想问的原因是因为这两个codeS输出同样的事情,所以我试图理解它为什么这样写。这里的code:

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:

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

这输出为:

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

所以我的问题是,什么是 $键=&GT之间的差异; $值或只是 $值的foreach 循环。该数组是多维的,如果有差别,我只是想知道为什么通过 $键 $值中在的foreach 循环。

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.

推荐答案

那么, $键=> $值在foreach循环是指关联数组的键值对,其中键作为指标来确定,而不是一个像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 code: $特色正在通过循环关联数组和为$关键=> $值表示,每次循环运行,并选择从阵列中键值对,它存储在本地 $键变量的关键在循环块,并在当地 $值变量的值内使用。因此,对于我们上面的例子数组,foreach循环将到达第一个键值对,如果你指定的为$关键=> $值,它将存储键1 $键变量和VALUE1 $值变量。

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.

既然你不使用 $键你的循环块内的变量,将它添加或移除它不会改变环路的输出,但它是最好的包括键值对,以表明它是一个关联数组。

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.

另外请注意,为$关键=> $值指定是任意的。你可以用替换为$富=> $栏,当你改变了循环块内的变量引用到新的变量,它会很好,只要努力, $ foo的 $栏。但让他们 $键 $值有助于跟踪他们的意思。

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.

这篇关于为$关键=>&QUOT之间的差异; $值"和"为$值"在PHP的foreach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-25 02:23