我想使用 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/