php - Multi row toJSON function using Propel and Backbone -
i'm trying make should simple "list all" function using propel orm - backbone.js read. want do, , in opinion, should work:
$users = usersquery::create() ->find(); echo $users->tojson();
however, when i'm running that, results i'm getting are:
{"users_0":{"id":1,"emailaddress":"sdf","password":"sdf","createdat":null,"modifiedat":null}, "users_1":{"id":2,"emailaddress":"dsf","password":"sdf","createdat":null,"modifiedat":null}}
whilst it's valid json, fact ever row array in main array throwing off json. need return json this:
[{"id":1,"emailaddress":"sdf","password":"sdf","createdat":null,"modifiedat":null},{"id":2,"emailaddress":"dsf","password":"sdf","createdat":null,"modifiedat":null}]
i've created below function (as test) , works perfectly, surely propel (or slim, framework i'm using) has way of stopping being inside array? here hack;
$users = usersquery::create() ->find(); $json = '['; foreach($users $user){ $json = $json.$user->exportto('json').','; } $json = $json.']'; echo str_replace("},]", "}]", $json);
any appreciated! all.
i hate it, think 1 of "that's how propel works" situations. said, improve helper function little more robust.
i put code in userquery class:
class usersquery extends baseusersquery { ... public function tojsonarray() { $users = $this->find(); $userarray = array(); foreach($users $user){ array_push($userarray, $user->toarray()); } return json_encode($userarray); } }
and use so...
$userjson = usersquery::create()->tojsonarray();
or if have other criteria...
$userjson = usersquery::create() ->filterbysomefield("somevalue") // other criteria ... ->tojsonarray();
Comments
Post a Comment