0

编辑:是因为 $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() 
4

2 回答 2

2

根据您的代码,$num == 0$_SESSION将永远不会被初始化,因此$_SESSION['first']将不存在。

于 2012-08-28T16:37:42.200 回答
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++;
}

文档

于 2012-08-28T16:36:48.453 回答