【问题标题】:Data column(s) for axis #0 cannot be of type string with google charts轴 #0 的数据列不能是带有谷歌图表的字符串类型
【发布时间】:2020-05-11 22:27:49
【问题描述】:

我正在使用 PHP 从 phpMyAdmin 数据库中填充 google 面积图。只有两列数据:日期和价格。以下是我的代码:

   <script type="text/javascript">
      google.charts.load('current', {'packages':['corechart']});
      google.charts.setOnLoadCallback(drawChart);

      function drawChart() {
        <?php
        $sql = "SELECT price, date FROM prices LIMIT 5;";
        $result = mysqli_query($conn, $sql);

        $data = [];
        while ($row = mysqli_fetch_assoc($result)) {
          $data[] = [$row['price'], $row['date']];
        }
        ?>
        var data = google.visualization.arrayToDataTable([<?= json_encode($data, JSON_NUMERIC_CHECK);?>]);

        var options = {
          title: 'Price History',
            hAxis: {
              title: 'Date',
              titleTextStyle: {color: '#333'}
            },
          vAxis: {
            minValue: 0,
            title: "price",
            format: 'currency',
            explorer: {
              actions: ['dragToZoom', 'rightClickToReset'],
              keepInBounds: true,
              maxZoomIn: 1.0}
            },
        };

我得到的 json 数据表如下所示:

[{"date":"2020-04-20 00:00:00","price":1},
{"date":"2020-05-09 18:05:02","price":1.02},
{"date":"2020-05-09 18:05:27","price":1.02},
{"date":"2020-05-09 18:05:06","price":1.0192233756},
{"date":"2020-05-09 18:05:35","price":1.0264162619}]

但是,我不断收到错误消息“轴 #0 的数据列不能是字符串类型”。在此之前我从未使用过谷歌图表,所以我什至不知道这意味着什么或如何解决它。

【问题讨论】:

    标签: javascript php json charts google-visualization


    【解决方案1】:

    google 的 arrayToDataTable 方法需要一个简单的值数组,
    没有对象/对象键...

    尝试只在 php 中添加值...

        $sql = "SELECT date, price FROM prices LIMIT 5;";
        $result = mysqli_query($conn, $sql);
        $data = [];
        while ($row = mysqli_fetch_assoc($result)) {
          $data[] = [$row['date'], $row['price']];  // <-- values only here
        }
    

    【讨论】:

    • 不幸的是,我在使用这种方法时遇到了同样的错误。
    • 请您分享绘制图表的其余代码吗? (编辑问题)
    • 我已经更新了问题以包含所有相关代码。
    猜你喜欢
    • 1970-01-01
    • 2014-04-20
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多