小编典典

为Google Charting API构建数组并格式化JSON

json

我正在使用Google Charting API的项目中工作,我想使用json填充图表以构建数据表。

作为测试,我尝试构建一个简单的数组,然后再尝试使用数据库中的动态数据进行处理,但是在以正确的格式获取json时遇到了问题。

在Google文档中,它表示json内容应位于以下内容中:

{
  "cols": [
        {"id":"","label":"Topping","pattern":"","type":"string"},
        {"id":"","label":"Slices","pattern":"","type":"number"}
      ],
  "rows": [
        {"c":[{"v":"Mushrooms","f":null},{"v":3,"f":null}]},
        {"c":[{"v":"Onions","f":null},{"v":1,"f":null}]},
        {"c":[{"v":"Olives","f":null},{"v":1,"f":null}]},
        {"c":[{"v":"Zucchini","f":null},{"v":1,"f":null}]},
        {"c":[{"v":"Pepperoni","f":null},{"v":2,"f":null}]}
      ]
}

我正在调用一个返回json代码的函数。

下面是该函数的调用方式

print json_encode(test());

测试功能是

function test()
{
    $array = array();
    $array['cols'][] = "20-01-13";
    $array['cols'][] = "21-01-13";
    $array['cols'][] = "22-01-13";
    $array['rows'][] = 22;
    $array['rows'][] = 26;
    $array['rows'][] = 12;

    return $array;
}

生成图表的javascript如下

<script>
            google.load('visualization', '1', {'packages':['corechart']});

            // Set a callback to run when the Google Visualization API is loaded.
            google.setOnLoadCallback(drawChart);

            function drawChart() {
                 var jsonData = $.ajax({
                 url: "loadGraph.php",
                 dataType:"json",
                 async: false
                }).responseText;

                var data = new google.visualization.DataTable(jsonData);

      // Instantiate and draw our chart, passing in some options.
      var chart = new google.visualization.PieChart(document.getElementById('lineGraph'));
      chart.draw(data, {width: 400, height: 240});
            }
        </script>

当我回显json时,它将以以下格式返回

{"cols":["20-01-13","21-01-13","22-01-13"],"rows":[22,26,12]}

如果我尝试将其用于Google图表的数据集,则会收到以下消息

Cannot read property of '1' of undefined

我只是在构建一个简单的折线图,它仅包含沿x轴的日期和沿y轴的日期在该日期发生了多少次的计数。

我该如何建立阵列,以正确的格式获取Google api图表。

感谢您的任何帮助,您可以提供。


阅读 240

收藏
2020-07-27

共1个答案

小编典典

需要 为cols 指定参数 类型 。请参阅Google Charts
JSON格式

您的PHP代码应类似于:

function test()
{
    $array['cols'][] = array('type' => 'string');
    $array['cols'][] = array('type' => 'string');
    $array['cols'][] = array('type' => 'string');

    $array['rows'][] = array('c' => array( array('v'=>'20-01-13'), array('v'=>22)) );
    $array['rows'][] = array('c' => array( array('v'=>'21-01-13'), array('v'=>26)));
    $array['rows'][] = array('c' => array( array('v'=>'22-01-13'), array('v'=>12)));

    return $array;
}

print json_encode(test());

您的json代码看起来更像:

{
  "cols": [
    {"type": "string"},
    {"type": "string"},
    {"type": "string"}
    ],
  "rows": [
    {"c":[{"v":"20-01-13"}, {"v":22} ]},
    {"c":[{"v":"21-01-13"}, {"v":26} ]},
    {"c":[{"v":"22-01-13"}, {"v":12} ]}
  ]
}
2020-07-27