我在php中有一个JSON数组,我想要做的是将它作为两个数组传递给java脚本,
[{"mon":"January","total":"29674"},{"mon":"February","total":"22956"},{"mon":"March","total":"35893"},{"mon":"April","total":"64003"},{"mon":"May","total":"43047"},{"mon":"June","total":"44613"},{"mon":"July","total":"72003"},{"mon":"August","total":"116742"}]
这里的数组应该是这样的,
var s1 = [January, February, March, April , ....];
var s2 = [29674, 22956, 35893, 64003, .....];
答案 0 :(得分:2)
抱歉截至目前我不知道如何使用jsfiddle。这是解决方案:
var b = [{"mon":"January","total":"29674"},{"mon":"February","total":"22956"},{"mon":"March","total":"35893"},{"mon":"April","total":"64003"},{"mon":"May","total":"43047"},{"mon":"June","total":"44613"},{"mon":"July","total":"72003"},{"mon":"August","total":"116742"}]
var x = [], y = [];
for (i = 0; i < b.length; i++){ x.push(b[i].mon); y.push(b[i].total) }
结果:
["January", "February", "March", "April", "May", "June", "July", "August"]
["29674", "22956", "35893", "64003", "43047", "44613", "72003", "116742"]
答案 1 :(得分:0)
首先,您必须遍历第一个数组并将其保存在单独的数组中。
<?php
$input = '[{"mon":"January","total":"29674"},{"mon":"February","total":"22956"},{"mon":"March","total":"35893"},{"mon":"April","total":"64003"},{"mon":"May","total":"43047"},{"mon":"June","total":"44613"},{"mon":"July","total":"72003"},{"mon":"August","total":"116742"}]';
$inputArray = json_decode($input, true);
$s1 = array();
$s2 = array();
foreach ($inputArray as $row) {
$s1[] = $row['mon'];
$s2[] = (int) $row['total'];
}
?>
然后你必须在你的剧本中打印它们:
<script>
var s1 = <?php echo json_encode($s1); ?>;
var s2 = <?php echo json_encode($s2); ?>;
</script>