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.
$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 );
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.
精彩评论