Codeigniter错误:致命错误:无法将CI_DB_mysql_result类型的对象用作数组


Codeigniter error : Fatal error: Cannot use object of type CI_DB_mysql_result as array

我正在尝试为树实现php代码点火器模型,每次运行控制器时,我都会收到以下错误:

致命错误:无法将CI_DB_mysql_result类型的对象用作中的数组C: 第50行上的''AppServ''www''tree''application''models''Btree.php

我试图在行中修复此语法

$currentID = $row['id'];

然而,仍然得到相同的错误消息。

我的模型功能是:

public function fetchTree($parentArray, $parentID = null)
{
    // Create the query
    if ($parentID == null)
        $parentID = -1;
    $sql = "SELECT `id` FROM `{$this->tblName}` WHERE `id`= ". intval($parentID);
    // Execute the query and go through the results.
    $result = $this->db->query($sql);
    if ($result)
    {
        while ($row = $result)
        {
            // Create a child array for the current ID
            $currentID = $row['id'];
            $parentArray[$currentID] = array();
            // Print all children of the current ID
            $this->fetchTree($parentArray[$currentID], $currentID);
        }
        $result->close();
    }
}

您的问题是这行:

while($row = $result)

您正在将$row设置为整个查询对象。您希望循环查询的结果

试试这个:

$query = $this->db->query($sql);
foreach($query->result_array() AS $row) {
    $currentID = $row['id'];
    ...

更简单的解决方案是直接转换为数组:

$result = $this->db->query($sql)->result_array();

尝试这个

    public function fetchTree($parentArray, $parentID = null)
{
     // Create the query
        if ($parentID == null)
            $parentID = -1;
    $sql = "SELECT `id` FROM `{$this->tblName}` WHERE `id`= ". intval($parentID);
    // Execute the query and go through the results.
    $result = $this->db->query($sql);
    if ($result)
    {
        while ($row = $result)
        {
            // Create a child array for the current ID
            $currentID = $row['id'];
            $parentArray[$currentID] = array();
            // Print all children of the current ID
            $this->fetchTree($parentArray[$currentID], $currentID);
        }
        $result->close();
    }
}