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 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配