Reputation: 2704
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
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
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