这个问题应该很容易解决,但通过反复试验和谷歌搜索,我没有答案。我正在尝试创建一个简单的循环,它将显示我的JSON变量中的值。
<p id="demo"></p>
<?php echo ($_SESSION['amort_JSON']);
?>
<script>
var obj, i, j, x = 0;
var obj = JSON.parse(<?php echo json_encode($_SESSION['amort_JSON']) ?>);
for (i in obj.interest_paid) {
x += obj[i].interest_paid;
}
//document.write(obj[8].interest_paid);
document.getElementById("demo").innerHTML = x;
</script>
$_session['anirt_JSON']
返回以下值
[{
"periodic_pmt": "2",
"principle_balance": 416997.37661705,
"principle_paid": 0,
"ttl_principle_paid": 1002.6233829502,
"interest_paid": 0,
"ttl_interest_paid": 866.83015878773
}, {
"periodic_pmt": 3,
"principle_balance": 416600.29804453,
"principle_paid": 538.02630958206,
"ttl_principle_paid": 1540.6496925323,
"interest_paid": 396.7004612869,
"ttl_interest_paid": 1263.5306200746
}, {
"periodic_pmt": 4,
"principle_balance": 416203.59758324,
"principle_paid": 538.40406076641,
"ttl_principle_paid": 2079.0537532987,
"interest_paid": 396.32271010256,
"ttl_interest_paid": 1659.8533301772
}]
感谢您的帮助。学习非常有趣。
答案 0 :(得分:0)
为了通过索引obj
(使用i
)访问obj[i]
数组中的每个项目,您需要迭代数组的所有可能索引值:{{1通过0
。
obj.length - 1
这指示JavaScript解释器:
for (var i = 0; i < obj.length; i++) {
开始,0
之前停止(即结束于obj.length
),obj.length - 1
。答案 1 :(得分:0)
由于obj是一个JSON对象数组,因此可以使用forEach循环来访问每个元素。
var obj = [{"periodic_pmt":"2","principle_balance":416997.37661705,"principle_paid":0,"ttl_principle_paid":1002.6233829502,"interest_paid":0,"ttl_interest_paid":866.83015878773},{"periodic_pmt":3,"principle_balance":416600.29804453,"principle_paid":538.02630958206,"ttl_principle_paid":1540.6496925323,"interest_paid":396.7004612869,"ttl_interest_paid":1263.5306200746}],
x=0;
obj.forEach(function (element, index) {
x += element.interest_paid;
});
console.log(x);
&#13;
答案 2 :(得分:0)
你的代码应该是
for (i in obj) {
x += obj[i].interest_paid;
}
obj
是解析过的json数组,你应该遍历它。 obj.interest_paid
不存在,因为obj
是一个对象数组。
这是Demo
<强> 编辑: 强>
正如@nnnnnn建议你应该在字符串周围加上引号。
JSON.parse('<?php echo json_encode($_SESSION['amort_JSON']) ?>');
答案 3 :(得分:0)
您正在解析不正确的JSON
对象。它应该是for (var i in obj) { ... }
而不是for (var i in obj.interest_paid) { ... }
。
工作演示
var jsonObj = [{
"periodic_pmt": "2",
"principle_balance": 416997.37661705,
"principle_paid": 0,
"ttl_principle_paid": 1002.6233829502,
"interest_paid": 0,
"ttl_interest_paid": 866.83015878773
}, {
"periodic_pmt": 3,
"principle_balance": 416600.29804453,
"principle_paid": 538.02630958206,
"ttl_principle_paid": 1540.6496925323,
"interest_paid": 396.7004612869,
"ttl_interest_paid": 1263.5306200746
}, {
"periodic_pmt": 4,
"principle_balance": 416203.59758324,
"principle_paid": 538.40406076641,
"ttl_principle_paid": 2079.0537532987,
"interest_paid": 396.32271010256,
"ttl_interest_paid": 1659.8533301772
}];
var x = 0;
for (var i in jsonObj) {
x += jsonObj[i].interest_paid;
}
console.log(x);