dongtai419309 2014-10-17 07:08
浏览 57
已采纳

在javascript中回显PHP数组

Answer from here : https://stackoverflow.com/a/12863675/894470 is how to assign array to variable.

I'm getting my data from php but when I echo it inside javscript like example below my chart wont draw.

var month_data= [<?php echo json_encode($lol); ?>];

but I can show alert and see all my data no problem like below:

enter image description here

If I copy the text from alert and paste it in array like below:

var month_data= [{month: '2014-01', KFC: 0, PizzaHut: 1},{month: '2014-03', KFC: 2, PizzaHut: 1},{month: '2014-04', KFC: 1, PizzaHut: 0},{month: '2014-05', KFC: 0, PizzaHut: 1},{month: '2014-07', KFC: 1, PizzaHut: 0},{month: '2014-10', KFC: 42, PizzaHut: 42}];

my chart will draw. What is wrong here??

UPDATE: My query:

$lol = array();
while ($row = mysqli_fetch_array($result)) {

    $lol[] =   "{month: '". $row['year'] ."-". $row['month'] ."', KFC: ". $row['kfc'] .", PizzaHut: ". $row['pizzahut'] ."}";
}

and I'm using Morris.js: http://morrisjs.github.io/morris.js/ to generate my chart.

  • 写回答

2条回答 默认 最新

  • drls2738 2014-10-17 07:37
    关注

    You need a real PHP structure to encode it into JSON, not just a string:

    $lol = array();
    while ($row = mysqli_fetch_array($result)) {
        $lol[] = Array(
            "month"    => $row['year'].'-'.$row['month'],
            "KFC"      => $row['kfc'],
            "PizzaHut" => $row['pizzahut']
        );
    }
    

    and:

    var month_data = <?php echo json_encode($lol); ?>;
    

    json_encode will automatically translate $lol into a json array containing objects (associative arrays are translated into objects).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看