json - 将 codeigniter 查询转换为 json?

标签 json codeigniter

我想使用 json_encode 将模型查询转换为 json,但不起作用。但对于普通数组却可以。

 $arr = array("one", "two", "three");
       $data["json"] = json_encode($arr);

输出

 <?php echo "var arr=".$json.";"; ?>
 var arr=["one","two","three"];

但是当我尝试转换查询时,codeigniter 会抛出错误。这是怎么回事? 这是错误消息:

A PHP Error was encountered Severity: Warning Message: [json] (php_json_encode) type is unsupported, encoded as null

转换后的“查询”结果=我的意思是模型方法如下:

{"conn_id":null,"result_id":null,"result_array":[],"result_object":[],"current_row":0,"num_rows":9,"row_data":null} 

我尝试这样做

 $posts = $this->Posts_model->SelectAll();
       $data["posts"] = json_encode($posts); 

顺便说一句,当我在没有 json_encode 的情况下执行此操作时,模型和方法工作得很好。

我可能做错了,但问题是什么呢?

最佳答案

您似乎正在尝试对 CodeIgniter 数据库结果对象而不是结果数组进行编码。数据库结果对象充当游标到结果集中的包装器。您应该从结果对象中获取结果数组,然后对其进行编码。

您的模型代码似乎是这样的:

function SelectAll()
{
    $sql = 'SELECT * FROM posts';
    // Return the result object
    return $this->db->query($sql);
}

应该更像这样:

function SelectAll()
{
    $sql = 'SELECT * FROM posts';
    $query = $this->db->query($sql);
    // Fetch the result array from the result object and return it
    return $query->result();
}

这将返回一个对象数组,您可以将其编码为 JSON。

尝试对结果对象进行编码时出现错误的原因是它有 resource无法用 JSON 编码的成员变量。这个资源变量实际上就是进入结果集的游标。

关于json - 将 codeigniter 查询转换为 json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2412574/

相关文章:

java - 我如何解析 JSON 的这种语法?

ruby-on-rails - 在表单 Rails 中创建多个对象

javascript - 来自 JSON 的自动完成文本框选项

codeigniter - 如何在 Codeigniter 上使用 Guzzle?

PHP Codeigniter 使用正则表达式 DRY 转换许多 IF

php - 在 Codeigniter 中使用 jQuery 将选项添加到 DropDownList

PHP 4.4.1 JSON 编码

json - 在javascript中导入json似乎没有成功

php - 使用 mysql 的最新 Xampp,来自 Xampp 版本 1.4.4

php - codeigniter 电子邮件功能 smtp 错误