D4v3 D4v3 - 1 year ago 72
Javascript Question

sending multidimensional array via ajax, index[0] problems

I'm trying to send a multidimensional array from php to Javascript/jQuery but I'm having a problem.

When I'm sending index 0 via

, the client receives the response in the format I want:


When I inspect with firebug, the index 0 array sent doesn't seem to arrive with JSON?

When I send any other index of the array, the client receives the array in this format(which I don't want):


when I inspect the arrays received by the client when the index is anything other than 0, I can clearly see that it was sent using JSON.

What's the problem, and how can I get all of my indexed arrays sent using the same format as my array[0] ?

Here's my php code:

$strJEncoded = json_encode($array);
echo $strJEncoded;

Here's my JS/Jquery code:

$res = jQuery.parseJSON(response);

Answer Source

By default, json_encode() will only produce a JSON array if the array indexes are sequential numbers starting from 0. Otherwise, it produces a JSON object.

You can use array_values() to return an array with the indexes renumbered from 0.

$strJEncoded = json_encode(array_values($array));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download