1

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?

3 Answers 3

4
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.

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

1 Comment

@Curtis You're welcome. Please accept this answer if it helped you/solved your problem ;)
0

try this way:

alert(window.MyArray.facebook.user);

it will work

Comments

0

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

Comments

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.