tags:

views:

429

answers:

2

I am using Doctrine 1.2, how could I get the query object into json / array format?

$user = Doctrine_Query::create()
->select('u.id, u.username, u.firstname, u.lastname')
->from('User u')
->orderby('u.id')
->execute();
+4  A: 

A solution might be to use the toArray() method on the $user object, to have a simple array containing only the data youre interested in, and, then, use json_encode to convert that PHP array to a JSON string.

Something like this, I suppose :

$user = Doctrine_Query::create()
->select('u.id, u.username, u.firstname, u.lastname')
->from('User u')
->orderby('u.id')
->execute();

$userArray = $user->toArray();
$json = json_encode($userArray);

(Not tested, but it should not be too far from working...)

Pascal MARTIN
This is how I do it.
Sam
A: 
$users2 = Doctrine_Query::create()
->select('u.id, u.username, u.firstname, u.lastname')
->from('User u')
->orderby('u.id');
$tmp2 = $users2->fetchArray();

I don't know why the toArray() will give the other field in the table, e.g. it will have the "password" field, it seems fetchArray() can give me the correct fields in query.

toArray()

Array
(
    [0] => Array
        (
            [id] => 1
            [username] => user1
            [password] => password
            [firstname] => John
            [lastname] => Smith
        )

fetchArray()

Array
(
    [0] => Array
        (
            [id] => 1
            [username] => user1
            [firstname] => John
            [lastname] => Smith
        )
cc96ai