PHP报告foreach()的参数无效.为什么


PHP reports invalid argument for foreach(). Why?

在以下代码中,$stu被声明为数组,但PHP报告foreach((的参数无效。为什么?



echo "<table align='center' border='1px'><tr><td>";
echo "<form action='".$_SERVER['PHP_SELF']."' method='POST'>";
$students=array("Jack","John","Ryan");
foreach ($students as $key=>$stu)
 {
echo "Please select a grade for $stu:";
echo "<select name='grade'>";
echo "<option>Grade A</option>";
echo "<option>Grade B</option>";
echo "<option>Grade C</option>";
echo "<option>Grade D</option>";
echo "<option>Grade E</option>";
echo "</select><br/>";
  }
for ($i=0;$i<count($students);$i++)
{
    echo "<input type='hidden' name='stu[]' value='$students[$i]'>";
}
foreach($stu as $arr_contents)
{
echo "$arr_contents";
}
echo "<input type='hidden' name='posted' value='true'>";
echo "<input type='submit' value='Enter'>";
echo "</form>";
echo "</tr></td></table>";
?>

$stu是在第一个foreach的作用域中定义的,它在自己的foreach中被调用之前是关闭的。在第一个foreach循环结束时,它将包含最后使用的字符串值"Ryan"。

// $stu is only known inside this block
foreach ($students as $key=>$stu)
{
}

如果要回显$stu的内容,则必须在第一个foreach循环中执行。

变量$students未声明为关联数组,值为数组。应该是这样的:
$students = array( "Jack" => array( 'array', 'contents' ), "John" => array( 'other', 'content') );