0

I am having a hard time transferring my php array of arrays to a json object.

Array(
    [28] => Array(
        [0] => Array(
            [0] => 1
            [1] => 5
        ) 
        [1] => Array(
            [0] => 1 
            [1] => 18
        )
        [424] => Array(
            [0] => Array(
                [0] => 1
                [1] => 5
            ) 
            [1] => Array(
                [0] => 1
                [1] => 18
            )
        )
     )
)

After I json_encode this structure in jQuery I use the .each and get the two arrays but I cant seem to grab the [28] and [424]. Any thoughts?

$.each(data, function(i, val) {
    console.log(val); // NAME ??
    console.log(data[i][0]); // LIST 1
    console.log(data[i][1]); // LIST 2
});
1
  • 1
    What does console.log(i) yield? Commented Aug 19, 2011 at 14:54

4 Answers 4

4
$.each(data, function(i, val) {
    console.log(i); // name
    console.log(val); //array
});
Sign up to request clarification or add additional context in comments.

Comments

1

JSON encodes keys as strings, which means that jQuery is looking for a string, not an integer. Try accessing the arrays using strings.

1 Comment

json_encode (no flags given) will encode the array keys as object member names, not array keys.
0

Try this

$.each(data, function(i, val) {
    //First iterration "this" will point to '28' array
    //Second iterration "this" will point to '424' array

    //You can use it like this, this[i][0]

});

Comments

0

The PHP array keys 28 and 424 will be represented in the javascript variable i inside the callback function.

Check the docs for $.each Docs, they explain it in detail.

1 Comment

Easy enough, the examples used 'i' and I assumed it was an integer all the time. Thanks!

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.