views:

31

answers:

1

So I've got an object containing several rows from a database (using PHP).

How should I organize them into an array to pass through JSON?

For example, say I want to list some users. I've already done the correct query, and have an object called $u

foreach($u as $user)
    {
        $rows['name'] = $user->firstname . $user->lastname;
    }

Now I'm new to JSON, and I'm trying to think of the easiest way to access the rows later. For this example I'd need to be able to access "name", "registered", and "id". How should I build up the array before I use json_encode();?

+2  A: 

Something like this would work nice...

$users = array(
    array(
            'name' => 'bob',
            'registered' => TRUE,
            'id' => $id
        ), ...
);

header('Content-Type: application/json');
echo json_encode($users);

(Obviously replace the variables and strings).

Here is some example output...

[{"name":"bob","registered":true,"id":7}]

As you can see, it is a JavaScript object which is the first member of the array.

If your library sends the XHR header (jQuery does) then you can also check for

($_SERVER['X_HTTP_REQUESTED_WITH'] === 'XMLHttpRequest')

You will probably also want to make sure that header exists with either isset() or array_key_exists(). Checking for this header is not necessary, but it can help when a file can be requested with AJAX or plainly requested and serve different views accordingly (JSON or HTML).

alex