Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
add comment

3 Answers

up vote 4 down vote accepted
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.

share|improve this answer
    
my bad, It was due to a typo, works great, thanks! –  Curtis Oct 27 '13 at 14:38
    
@Curtis You're welcome. Please accept this answer if it helped you/solved your problem ;) –  ComFreek Oct 27 '13 at 15:00
add comment

try this way:

alert(window.MyArray.facebook.user);

it will work

share|improve this answer
add comment

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

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.