0

I have an multidimensional array

$array = array(
    "Level1"=>array(
        "Level11"=>array(
            "level111"=>'value1',
            "level112"=>'value2',
            ),
        "Level12"=>array(
            "level121"=>'value1',
            "level122"=>'value2',
            ),
        ),
    "Level2"=>array(
        "Level21"=>array(
            "level211"=>'value1',
            "level212"=>'value2',
            ),
        "Level22"=>array(
            "level221"=>'value1',
            "level222"=>'value2',
            ),
        )
    );
echo json_encode($array);

This encoded JSON is sent after receiving AJAX POST request using jQuery.

$.post(
    'mypage.php',
    {
        param1: value1,
        param2: value2
    },
    function(data) {
        //Now I can access the 1st level JSON value easily like
        alert(data.Level1); 

        // But

        // I am trying to access the values like 

        alert(data.Level1.Level11.level112); //which is not possible
    },
    "json"
);

If you have understood my question, do you know how I could tackle this problem.

4
  • 2
    Why is data.level1.level11.level112 not possible? Commented Nov 12, 2010 at 10:43
  • Have you checked what string is generated by json_encode()? Btw even data.level1 should not work, because the key is named Level1 (capital L). Commented Nov 12, 2010 at 10:48
  • @Pekka, I dont know, that code was supposed to work, but it didn't. @Felix Kling, Yes it can be accesed as array, like dt = data.level1; i = dt['level11'][level112] and I just created a sample of my code, I will correct it right away, I have 3 more levels in my actual code. Commented Nov 12, 2010 at 10:51
  • Works for me: jsfiddle.net/KjHJd (JSON generated by codepad.org/jUiDCeq6), the error must be somewhere else. You should get some error message on the console. Commented Nov 12, 2010 at 10:57

1 Answer 1

1

Ok, my guess: You use capital letters in some of your keys in PHP but not in JS. Your line should be:

data.Level1.Level11.level112

Note that it is Level1 with captial L, not level1.

DEMO

Sign up to request clarification or add additional context in comments.

4 Comments

@Starx: Well, then you should provide a better example. As you can see in the demo, this would be what json_encode generates. And it is accessible.
I am a bit confused now, It wasn't working in my case, That means there must be another point I am missing. I will check it out. Tnx, for showing me the demo.
Are you sure the encoded JSON from PHP, is exactly like that in you fiddle?
@Starx: I copy and pasted it from codepad.org/jUiDCeq6. But nevertheless, make sure that your server is generating the right JSON.

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.