CodeIgniter:PHP错误:Table.php中的foreach()中的arg无效:第198行

我已经对这个错误进行了非常彻底的搜索,尽管我找到了许多有关“确保您正在传递数组或SQL查询”的一般答案,但我认为每个CodeIgniter库都需要更具体的帮助.

我有一个只应创建查询(或数组)并生成表的视图.

(最终,查询将来自模型,并且表生成将是我的控制器中的一个函数,因此我可以在其他视图中重用它,但是我只是从基本的回显屏幕开始)

视图设置如下:

<div class="span4 well well-small">
            <h4>Requests:</h4>
            <?php
                $this->table->set_heading('ID', 'Request', 'User', 'Date');

                $query = array('id'=>'123', 'request'=>'FARTS', 'user'=>'Steve', 'date'=>'Today'); //$this->db->select('user_id', 'password', 'user_name', 'company_id')->from('users');
                echo $this->table->generate($query);
            ?>
            <h4>In this div:</h4>
            <p>we will display some information about recent requests. It will show a small table with Request ID, Request Name, and Date Requested headers.</p>
</div>

这将显示一个带有4个PHP错误框的框,其中显示:

遇到PHP错误

严重程度:警告

消息:为foreach()提供了无效的参数

文件名:libraries / Table.php

行号:198

当我检查Table.php库中的第198行时,它需要一个数组(关联的或非关联的)或来自数据库的查询.我试图传递一个非关联数组,一个关联数组和一个数据库查询,所有这些都会产生相同的错误.

并且,因此您不必遍历CI,这是引发错误的函数:

function _prep_args($args)
{
    // If there is no $args[0], skip this and treat as an associative array
    // This can happen if there is only a single key, for example this is passed to table->generate
    // array(array('foo'=>'bar'))
    if (isset($args[0]) AND (count($args) == 1 && is_array($args[0])))
    {
        // args sent as indexed array
        if ( ! isset($args[0]['data']))
        {
            foreach ($args[0] as $key => $val)
            {
                if (is_array($val) && isset($val['data']))
                {
                    $args[$key] = $val;
                }
                else
                {
                    $args[$key] = array('data' => $val);
                }
            }
        }
    }
    else
    {
        foreach ($args as $key => $val)
        {
            if ( ! is_array($val))
            {
                $args[$key] = array('data' => $val);
            }
        }
    }

    return $args;
}

解决方法:

将$query变量更改为如下形式:

$query = array(array('id'=>'123', 'request'=>'FARTS', 'user'=>'Steve', 'date'=>'Today'));

即使没有特定的key =>值对,该方法也需要一个数组数组.

$query = array(array('123','FARTS','Steve', 'Today'));

本质上,这也是使用CI的数据库库时数据库查询应返回的内容.

就个人而言,除非您直接使用db查询中的数据,否则我将使用:

$this->table->add_row('123','FARTS','Steve', 'Today');
-OR-
$this->table->add_row(array('ID'=>'hello','class'=>'Today','data'=>'Displayed Text'));

至于您的数据库查询遇到相同的错误,我将三重检查您实际上从所述查询接收的输出是哪种.

希望这可以帮助

上一篇:jQuery AJAX调用PHP控制器


下一篇:php-CodeIgniter“ default_controller”函数在URL中没有控制器名称