尝试使用JQuery从PHP JSON多维数组中获取数据的问题
I have a multidimensional array which, when echoed in PHP, looks like this:
{
"11-12-20":{"visits":0,"pageviews":0}
"11-12-21":{"visits":0,"pageviews":0}
"11-12-22":{"visits":0,"pageviews":0}
}// etc.
As you can see, the date is the key to the arrays inside the multidimensional array. So I can select an array from the multidimensional array using the date as the key:
$my_multi_array['12-12-12'];
JSON:
$.getJSON('file.php', function(data){
var test='11-12-29';
document.write(data.test);
});
When I test that in a browser, nothing is printed on the screen. Also, how would I go about looping through the whole of that array in jQuery and use the data inside that array's array.
I've been at this for hours now, and am pretty frustrated.
我有一个多维数组,当在PHP中回显时,它看起来像这样: p>
{
“11-12-20”:{“visits”:0,“pageviews”:0}
“11-12-21”:{“visits”:0,“pageviews” :0}
“11-12-22”:{“visits”:0,“网页浏览量”:0}
} //等等
code> pre>
如您所见,日期是多维数组中数组的关键。 所以我可以使用日期作为键从多维数组中选择一个数组: p>
$ my_multi_array ['12 -12-12'];
code>
JSON:
nn$.getJSON('file.php',function(data){
var test = '11 -12 -29';
document.write(data.test);
});
code> pre>
当我在浏览器中测试时,没有任何内容打印在 屏幕。 另外,我如何在jQuery中循环遍历整个数组并使用该数组的数组中的数据。 p>
我已经在这里工作了好几个小时了,我很沮丧 。 p>
div>
The PHP output that you have echoed is not an array, it's a JSON object without comma separators, which means it's not correctly formed.
If you correct the syntax, you can access the objects in data through the index notation ([]), not the dot operator (.). So instead of accessing data
like data.test
, you should try data[test]
.
Assuming you name your JSON object myJson
, here's how you can iterate thought it:
var myJson = {
"11-12-20":{"visits":0,"pageviews":0},
"11-12-21":{"visits":0,"pageviews":0},
"11-12-22":{"visits":0,"pageviews":0}
}
for (var item in myJson)
{
alert(myJson[item].visits + ", " + myJson[item].pageviews);
}
Use data[test]
. Your data.test
is equal to data["test"]
, and there is no "test" property in your object.