1

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           // 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.

1
  • Could you include the JSON output that is incorrect? Commented Sep 20, 2011 at 11:45

1 Answer 1

3

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}}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.