Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/image/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 无效参数_Php_Foreach - Fatal编程技术网

Php 无效参数

Php 无效参数,php,foreach,Php,Foreach,编辑:是因为$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被初始化为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++;
}
我得到的错误: (一旦我刷新页面,它就会消失)


在使用
is_array
循环之前,请确保变量是数组:

$i = 1;
if (is_array($_SESSION['first'])) { foreach ($_SESSION['first'] as $names) {
    //do something with $_SESSION['second'][$i];
    $i++;
}}
问题可能来自最初将值放入数组的方式,可以使用
is\u 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++;
}
$i=1;
如果(!是_数组($_会话['first']))
$\u会话['first']=array();
//查询以从数据库中选择元组;
而我首先;
$\会话['second'][$i]=$row->second;
$i++;
}
文档

  • 是数组
    -
  • foreach
    -

基于您的代码,当
$num==0
您的
$\u会话将永远不会初始化,因此
$\u会话['first']
将不存在。

在调用
foreach
之前是否验证
$\u会话['first']
是数组?是的。我使用了:print\u var($\u会话['first']);//显示索引为1=Somevalue的数组。出现错误时如何处理?首先是显而易见的解决方案:您是否确实在运行
会话\u start()
?如果
$\u会话['first']
如果是一个数组,则不会出现错误。$num肯定会大于0。亲爱的vgkuttu。我打赌$num小于或等于0。如果不是,我会非常非常惊讶。如果你将整个代码放入
if($num>0).
中,它应该会消失。注意-我把我的php知识放在赌注上;)你可能是对的。但是,我可以向你保证$num至少是1。亲爱的vgkuttu。如果
$num
为>0且显示错误,则我的判断不正确。除非在您向我们展示的这两段代码之间发生了更多的事情。最好的方法是,如果将此
if($num>0)
添加到
foreach
前面。如果您看到错误,则在到达
foreach
循环之前,
$\u会话将被删除。很抱歉,这是不可能的。为foreach()提供的错误
无效参数
表明数组未传递给
foreach
。如果向它传递数组,它不会抛出该错误。您没有检查它是否是数组,或者错误不是来自您在问题中输入的代码。问题不在于缺少
$\u会话['first']
,而在于根本没有
$\u会话
。可能没有足够的细节来确定这一点。只需调用
会话\u start
即可改变一切。
$i = 1;
if (is_array($_SESSION['first'])) { foreach ($_SESSION['first'] as $names) {
    //do something with $_SESSION['second'][$i];
    $i++;
}}
$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++;
}