I am trying to convert a MySQL query result into JSON within an AJAX request. My code looks like this at the moment.
$offset = empty($_GET['offset']) ? 0 : $_GET['offset'];
$numimagestodisplay = 3;
$items = array();
$allitems //开发者_如何学Python This is the queryset obtained through a call to a function
foreach ($allitems as $i => &$item)
{
if (($i >= $offset) && (count($items) < $numimagestodisplay))
{
$items[$i] = $item;
}
}
$output = '{"items":'.json_encode($items).'}';
I then want to cycle through the returned results in the javascript calling the above code and need to refer to the array items by their keys (I need to alter some HTML element IDs using these values). However, the JSON is returned in the wrong format.
If I change the line
$items[$i] = $item;
to:
$items[] = $item;
Then I can refer to it by key, however the keys are obviously just 0, 1, 2, whereas I need the key to be the value defined in the loop.
How can I alter the PHP code to return the JSON in the correct format?
Any advice appreciated.
Thanks.
The problem is that arrays in Javascript (and most other languages for that matter) can't have user defined keys. You want your array to be encoded to a JSON object instead of an array (arrays in PHP with user-defined keys are in essence objects). This usually happens automatically, for arrays with non-numeric keys.
In your case, you can use the JSON_FORCE_OBJECT
flag:
$output = '{"items":'.json_encode($items,JSON_FORCE_OBJECT).'}';
From the documentation:
Non-associative array output as array: [[1,2,3]]
Non-associative array output as object: {"0":{"0":1,"1":2,"2":3}}
精彩评论