Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly format JSON string in Codeiginiter?

My Codeiginiter application retrieves the data from database and stores it in the $result variable and this is then converted to JSON and I get code below:

 $data = $query->result_array();  
    $result['result'] = $data;



   { "result":[
    {"name":"John","surname":"Smith"}] }

However I want to get following JSON code but didn't have any success. Count represents number of rows. Any ideas? Thanks

{
"count": 8,
"result":[
{"name":"John","surname":"Smith"}] }
like image 973
GuyWhoReadsStockoverflow Avatar asked Dec 05 '25 16:12

GuyWhoReadsStockoverflow


1 Answers

I assume you're calling json_encode on the $result array?

Try the following:

$data = $query->result_array();  
$result['result'] = $data;
$result['count'] = count($data);

echo json_encode($result);
like image 109
Mike Avatar answered Dec 08 '25 05:12

Mike



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!