Mr.Z Mr.Z - 2 months ago 7
JSON Question

Convert result_array() to JSON object

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:

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


my attempt by studying several SO questions :

$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?

Example:

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

Answer

Try to return the query result not result_array

model function

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

Convert to json

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