这段代码有什么作用?(2)

Del*_*ens 1 php foreach

我不明白=>部分.

foreach ($_POST[‘tasks’] as $task_id => $v) {
Run Code Online (Sandbox Code Playgroud)

它在foreach循环中做了什么?

Jam*_*ore 12

foreach循环遍历数组中的每个项目,就像for循环一样.在这种情况下,$ task_id是键,$ v是值.例如:

$arr = array('foo1' => 'bar1', 'foo2' => 'bar2');
foreach ($arr as $key => $value)
{
  echo $key; // Outputs "foo1" the first time around and "foo2" the second.
  echo $value; // Outputs "bar1" the first time around and" bar2" the second.
}
Run Code Online (Sandbox Code Playgroud)

如果没有指定键,如下例所示,它使用默认索引键,如下所示:

$arr = array('apple', 'banana', 'grape');
foreach ($arr as $i => $fruit)
{
  echo $i; // Echos 0 the first time around, 1 the second, and 2 the third.
  echo $fruit;
}

// Which is equivalent to:
for ($i = 0; $i < count($arr); $i++)
{
  echo $i;
  echo $arr[$i];
}
Run Code Online (Sandbox Code Playgroud)

  • 实际上,我认为最好说所有PHP数组都是关联数组.默认情况下,键是基于0的整数值,但您可以将其设置为任何您想要的值. (2认同)