Curtis
Curtis

Reputation: 2704

Accessing JSON encoded PHP Array in jQuery

I have an PHP Array which is formatted in the following format :

$jsonArray = array(
    "facebook" => array("user" => "8", "user_id" => "10", "user_post" => "6"),
    "twitter" => array("user" => "8", "user_id" => "10", "user_post" => "6")
);

I've then done the following so I can access the array

echo "<script type='text/javascript'>window.MyArray = ".json_encode($jsonArray).";</script>";

And to access the array I tried the following

alert(window.MyArray['facebook'][0]['user']);

yet that's seemed to fail, any directions?

Upvotes: 1

Views: 436

Answers (3)

Tomer
Tomer

Reputation: 17930

You are passing the json as a string, you need to convert it to an object. To do that you can use http://www.json.org/js.html

Upvotes: 0

johnode
johnode

Reputation: 740

try this way:

alert(window.MyArray.facebook.user);

it will work

Upvotes: 0

ComFreek
ComFreek

Reputation: 29414

window.MyArray['facebook'][0]['user']
--------------------------^^^

Why do you need [0] here?

Use this:

window.MyArray['facebook']['user']

MyArray gives this:

{
    "facebook": {
        "user": "8",
        "user_id": "10",
        "user_post": "6"
    },
    "twitter": {
        ...
    }
}

MyArray['facebook'] results in the following array:

{
    "user": "8",
    "user_id": "10",
    "user_post": "6"
}

Therefore, MyArray['facebook']['user'] results in 8.

Upvotes: 4

Related Questions