views:

727

answers:

1

Hi, I'm trying to use the PHP json_encode function to encode some JSON to send along to a jQuery plugin that will render out a calendar. The plugin's name is FullCalendar.

I've started on grabbing event data from a MySQL database and encoding it in a JSON string, but I've run into a problem. The default JSON example that comes with the plugin works just fine, but mine does not.

Here is the example code - link | Here is the output - link

Here is my code - link | Here is the output - link

If you look at the outputs, there are suttle differences, but I believe that these differences are what is making it not work. You'll see that in the example output, there are brackets [] around everything, and containing each individual JSON string is just the curly braces {}. In my output, there are just curly braces {} containing each string, no brackets on the outside.

Help please? This is my first time using JSON!

+5  A: 

You're echoing each string separately, so json_encode never knows it's a list.

You could change your while statement to build up the list:

while($row = $result->fetch_array(MYSQLI_ASSOC))
{
    echo json_encode(array( 
    ....

to

$rows = array();
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
     $rows[] = array( 
     ....
}

then json_encode the whole thing:

echo json_encode($rows);

That will output the [{...},{...}] structure you're looking for, which is a valid JSON object.

Peter Stone
http://snipplr.com/view/17084/response-code/That's the code I'm using and the output at the bottom, why does it have the extra [] part at the beginning, then the second [] is what I want?
Dixon Crews
Take the "echo json_encode($rows)" out of the while loop. so: "while (fetch_array) { $rows[] = array(); } echo json_encode...."You want to build up the array in your loop, then json_encode the whole thing afterwards.
Peter Stone
Thanks a lot, everything's working great now!
Dixon Crews
+1 you want json_encode to be the LAST thing you do after organizing the information into an object, not trying to combine a bunch of JSON strings
micmcg