David Rhoden
David Rhoden

Reputation: 952

json_encode only returns the first element of an array?

I am using json_encode to create a JSON object from an array. They array is a couple hundred elements long, but json_encode appears to only give back the first element of the array.

Is this a limitation of json_decode, or am I using the wrong syntax to read the JSON object?

A little code: I create the array in PHP:

$getarrayforjson = mysql_fetch_array($result);

And in the javascript, I made it a variable:

var my_array = <?php echo json_encode($getarrayforjson); ?>

Typing 'my_array' in the console gives me a nice JSON-looking response, but only for the first element.

When I use the JSON in the code, like my_array.title, or my_array[4], I always get the same result.

I think my syntax is wrong, but am not sure how to fix it. I'm new to using json_encode.

Upvotes: 2

Views: 5127

Answers (2)

elu-nexlab
elu-nexlab

Reputation: 31

Try using print_r() or print() instead of echo.

var my_array = <?php print_r(json_encode($getarrayforjson)); ?>

I've run into this issue myself and it has confused me as well. json_encode() returns a string and as such I'd expect echo would return the entire string to be decoded, but in some instances it does not.

Upvotes: 0

Berry Langerak
Berry Langerak

Reputation: 18859

$getarrayforjson = mysql_fetch_array($result);

That is only one result. Try this:

<?php
while( $row = mysql_fetch_array( $result ) ) {
    $json[] = $row;
}
echo json_encode( $json );

Upvotes: 11

Related Questions