编辑:是因为$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()
根据您的代码,$num == 0
时,您的$_SESSION
永远不会被初始化,因此$_SESSION['first']
将不存在。
在使用 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++;
}
文档
-
is_array
- http://php.net/manual/en/function.is-array.php -
foreach
- http://php.net/manual/en/control-structures.foreach.php