我在PHP 中有这个数组
<?php
$data = array();
$data[0] = array('year' => 2001, 'month' => array(
'January' => array('val1' => 1000, 'val2' => 2000),
'February' => array('val1' => 1000, 'val2' => 2000)
)
);
$data[1] = array('year' => 2002, 'month' => array(
'January' => array('val1' => 3000, 'val2' => 4000),
'February' => array('val1' => 6000, 'val2' => 7000)
)
);
echo json_encode($data);
?>
我正试图从javascript访问这个数组的属性,但我还没有访问。
我试过这个
<html>
<head>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: 'ajax1.php',
type: 'GET',
dataType: 'json'
}).done(function (data) {
var i = 0;
for (i in data) {
$('#year').append('<b>'+data[i].year+'</b>'+':<br/>');
var x=0;
for(x in data[i].month){
$('#year').append(data[i].month[x] +'<br/>');
x++;
}
i++;
}
});
});
</script>
<title>Graphs</title>
</head>
<body>
<div id="year">
</div>
</body>
</html>
我可以访问年份,但不能访问其他属性。
打印以下内容:
2001:
[object Object]
[object Object]
2002:
[object Object]
[object Object]
解码用PHP JSON_encode创建的JSON后,非数字数组将转换为Javascript对象。如果您需要数组,请尝试使用数字关键字。
一些浏览器,如chrome,按照对象关键字的字母顺序进行排序。如果您正在考虑迭代对象,则需要事先知道这一点。
建议:使用$.each i jQuery来迭代数组或对象更简单。
$.each(data, function(key, value){
...
});
因为每个月都是一个数组,所以不需要额外的循环来获取该月份数组中的值。其结果是:
$('#year').append(data[i].month[x][0] //= val1 within month[x]
$('#year').append(data[i].month[x][1] //= val2 within month[x]
所以你需要三个嵌套的循环:
//pseudo code including a new loop "z"
[i] to get the year;
[x] to get each month within year[i];
[z] to get each value within month[x];