0

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 json_encode($array);, the client receives the response in the format I want:

[[0,0],[1,0.031410759078128],[2,0.062790519529313],[3,0.094108313318514].etc..]

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):

{"1":[1,0.031410759078128],"2":[2,0.062790519529313],"3":[3,0.094108313318514].etc..}

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);
1
  • That second format is not a JSON array. It's an object with numeric keys whose values are themselves arrays. Commented Sep 7, 2016 at 23:17

1 Answer 1

2

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

2 Comments

Thank you, my client receives the correct array format now!
@D4v3 you should accept check this answer if this did solve your problem

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.