编辑:是因为$ i被初始化为1而不是0 ...... ???
我将从数据库中检索的某些值存储在会话变量中。这就是我这样做的方式:
$i = 1;
//query to select tuples from the database;
while($i <= $num) //$num is the count of the rows returned by the query
{
$_SESSION['first'][$i] = $row->first;
$_SESSION['second'][$i] = $row->second;
$i++;
}
然后我按如下方式使用它们:
$i = 1;
foreach ($_SESSION['first'] as $names)
{
//do something with $_SESSION['second'][$i];
$i++;
}
我得到的错误: (刷新页面后消失了)
Invalid argument supplied for foreach()
答案 0 :(得分:2)
根据您的代码,当$num == 0
永远不会初始化您的$_SESSION
时,$_SESSION['first']
将不存在。
答案 1 :(得分:0)
在使用is_array
:
$i = 1;
if (is_array($_SESSION['first'])) { foreach ($_SESSION['first'] as $names) {
//do something with $_SESSION['second'][$i];
$i++;
}}
问题可能来自您最初将值放入数组的方式,可以使用is_array
轻松纠正
$i = 1;
if (!is_array($_SESSION['first']))
$_SESSION['first'] = array();
//query to select tuples from the database;
while($i <= $num) //$num is the count of the rows returned by the query
{
$_SESSION['first'][$i] = $row->first;
$_SESSION['second'][$i] = $row->second;
$i++;
}
<强>文档强>