0

When using an array in a foreach loop

$stdlist = rtrim(trim($_POST['stdlist'], '/'), '/');
$stdlist = explode('/' , $stdlist);
print_r($stdlist);
foreach($stdlist as $value)
{
    echo "<br>";
    echo $_POST[$value];
}

the array $stdlist is clearly working; when printed this returns:

Array ( [0] => 1 [1] => 6 [2] => 7 [3] => 8 )

My problem is that when I use the foreach loop to extract out of the array one value at a time, the following gets printed to the page:

4
4
Notice: Undefined offset: 7 in C:\Program Files\wamp\www...on line 35
Notice: Undefined offset: 7 in C:\Program Files\wamp\www...on line 35

I know this isn't functioning as intended as I am expecting the following:

1
6
7
8

Could somebody please explain why this is happening and how to fix this issue? Thanks :-)

4

4 回答 4

3

您必须打印因为$value原始$value数组值而不是索引。而且你正在$stdlist从爆炸这个帖子变量中得到数组$_POST['stdlist']

foreach($stdlist as $value)
{
  echo "<br>";
  echo $value;
}

现在您将获得所需的结果。

于 2013-08-13T13:44:50.247 回答
0
foreach($stdlist as $value)
{
  echo "<br>";
  echo $value;
}

当你使用 foreach 时 $value 不是数组中的位置,如果你想使用你需要做的位置

for($pos=0; $pos<sizeof($stdlist); $pos++)
{
  echo "<br>";
  echo $stdlist[$pos];
}
于 2013-08-13T13:53:58.290 回答
0

当您对数组使用 foreach 循环时,而不是echo $_POST[$value];仅使用 use ,而是自动提取每个节点上的值。echo $value

foreach ($array as $index=>$value){
   echo "index is $index and value associated with it is $value.";
}

希望这可以帮助。

于 2013-08-13T13:48:39.403 回答
0

使用 foreach() 循环时,我建议将位置和值都分配给它们各自的变量,然后将它们打印到屏幕上以查看 foreach 循环如何分配值。

foreach( $stdlist as $position => $value ) {
   echo "The current position is $position, and the value of \$stdlist[$position] is
   $value";
}
于 2013-08-13T13:55:29.843 回答