将result_array()转换为JSON对象

时间:2021-04-03 21:16:23

What i am trying to do is convert result_array() given by my query and directly convert it into JSON object , which can further be set in controller like this:

我想要做的是转换我的查询给出的result_array()并直接将其转换为JSON对象,这可以进一步在控制器中设置如下:

$this->response($jsonobject, REST_Controller:: HTTP_OK);

my attempt by studying several SO questions :

我通过研究几个SO问题尝试:

$this->response(json_encode($result_array), REST_Controller:: HTTP_OK);

but my attempt is wrong i think because it return json itself in form of string , how to achieve this then?

但我认为我的尝试是错误的,因为它以字符串的形式返回json本身,如何实现呢?

Example:

例:

$pakistan = array('status' => 'OK','message' => 'yes i am ok');
// convert pakistan to something like
$pakistan = [ 'status' => 'OK','message' => 'yes i am ok' ];

1 个解决方案

#1


2  

Try to return the query result not result_array

尝试返回查询结果而不是result_array

model function

模型功能

function getRecords(){
   $sql = 'SELECT * FROM table';
   $query = $this->db->query($sql);
   return $query->result();
}

Convert to json

转换为json

$object = getRecords();
$json_obj = json_encode($object);

#1


2  

Try to return the query result not result_array

尝试返回查询结果而不是result_array

model function

模型功能

function getRecords(){
   $sql = 'SELECT * FROM table';
   $query = $this->db->query($sql);
   return $query->result();
}

Convert to json

转换为json

$object = getRecords();
$json_obj = json_encode($object);