Giacomo P. Sat Oct 16 09:48:25 -0400 2010

Subject: JSON encoding

Hi all,
I need to create a JSON encoded string of the results of a query, is there an example on how to do this?

Thanks to all


Kien La Sun Oct 24 12:34:25 -0400 2010
Giacomo P. Sat Nov 13 04:58:57 -0500 2010

I'm back ...
The example shows how to work with only one results, but I need to encode to JSON an array of results.
Is there another way?

Thanks

Kien La Mon Nov 15 21:01:11 -0500 2010

Currently, you'd just have to iterate over the results and call to_json() on each. Not really ideal but I'll be addressing this in a future version.

Fabien Maître Mon Jul 23 11:18:30 -0400 2012

Hi,
Sometimes you'll need to have double quotes for each values of the JSON string (for example for using jQuery EasyUI DataGrid). Here's a way to do this :

$result = array();
$persons = Person::find('all');
foreach ($persons as $p) {
array_push($result, $p->to_json());
}

$result = "[".implode(",", $result)."]";
$result = str_replace('":', '":"', $result);
$result = str_replace(',"', '","', $result);
$result = str_replace('""', '"', $result);

Rafael Izidoro Wed Aug 08 16:46:03 -0400 2012

+1 for toJson on results iterator!

Rafael Izidoro Wed Aug 08 19:54:34 -0400 2012

I found a good way to achieve this :

$result = array();
$persons = Person::all();

foreach($persons as $person) {
array_push($result, $person->to_array()); //using to_array instead of to_json
}

echo json_encode($result);

Fabien Maître Thu Aug 09 08:54:42 -0400 2012

Your solution didn't work for me. I have a Fatal error with message 'Call to undefined method: to_array'.
What version of PHP ActiveRecord do you use?

Rafael Izidoro Thu Aug 09 09:48:36 -0400 2012

The README shows 1.0, butI think it's the Nightly Build, cause I get the lib with Composer, and set the version to "dev-master". Take a look at my composer.json file:

{
"require" : {
"slim/slim" : "1.6.*",
"php-activerecord/php-activerecord" : "dev-master"
}
}

(1-8/8)