在jQuery中访问JSON编码的PHP数组

在jQuery中访问JSON编码的PHP数组

问题描述:

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?

我有一个PHP数组,其格式如下: p>

   $ jsonArray = array(
“facebook”=&gt; array(“user”=&gt;“8”,“user_id”=&gt;“10”,“user_post”=&gt;“6”),\  n“twitter”=&gt;数组(“user”=&gt;“8”,“user_id”=&gt;“10”,“user_post”=&gt;“6”)
); 
  code>  
 
 

我已经完成了以下操作,因此我可以访问数组 p>

  echo“&lt; script type ='text / javascript'&gt  ; window.MyArray =“。json_encode($ jsonArray)。”;&lt; / script&gt;“; 
  code>  pre> 
 
 

为了访问数组,我尝试了以下内容 p>

 警报(window.MyArray [ '实'] [0] [ '用户']); 
 代码>  PRE> 
 
 

还 这似乎是失败的,任何方向? p> div>

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.

try this way:

alert(window.MyArray.facebook.user);

it will work

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