【问题标题】:Chart.js variable data how can i make this work?Chart.js 可变数据我怎样才能使这项工作?
【发布时间】:2019-07-04 16:05:04
【问题描述】:

我试图在我的 Chart.js 中使用一个 php 变量作为数据,但我就是无法让它工作。这是我的尝试之一。

print_r($data); 的结果

$data = 129.74, 130.74, 129.50, 129.10, 129.80, 129.74, 129.90, 129.74

还有我的代码(我把它缩短了,这样更容易阅读)

<div>
<?php
  $sth = $db->prepare("SELECT Actual FROM csvhoejde1");
  $sth->execute();

  /* Fetch all of the remaining rows in the result set */
  $result = $sth->fetchAll(PDO::FETCH_COLUMN, 0);
  $result = explode("@", implode(",@", $result));
  // print_r for at se resultaterne.
  foreach ($result as $data) {
    echo'<pre>';
    print_r($data);
    echo'</pre>';
  }
?>

这是我的 chart.js 脚本

  <script src="./assets/charts/dist/Chart.js"></script>
  <script>

  var jArray = <?php echo json_encode($data); ?>;


  var canvas = document.getElementById("myChart");
  var ctx = canvas.getContext("2d");

  var horizonalLinePlugin = {
    afterDraw: function(chartInstance) {
      var yScale = chartInstance.scales["y-axis-0"];
      var canvas = chartInstance.chart;
      var ctx = canvas.ctx;
      var index;
      var line;
      var style;

      if (chartInstance.options.horizontalLine) {
        for (index = 0; index < chartInstance.options.horizontalLine.length; index++) {
          line = chartInstance.options.horizontalLine[index];

          if (!line.style) {
            style = "rgba(169,169,169, .6)";
          } else {
            style = line.style;
          }

          if (line.y) {
            yValue = yScale.getPixelForValue(line.y);
          } else {
            yValue = 0;
          }

          ctx.lineWidth = 3;

          if (yValue) {
            ctx.beginPath();
            ctx.moveTo(0, yValue);
            ctx.lineTo(canvas.width, yValue);
            ctx.strokeStyle = style;
            ctx.stroke();
          }

          if (line.text) {
            ctx.fillStyle = style;
            ctx.fillText(line.text, 0, yValue + ctx.lineWidth);
          }
        }
        return;
      };
    }
  };
  Chart.pluginService.register(horizonalLinePlugin);

  var data = {
    labels: ["1", "2", "3", "4", "5", "6", "7","8", "9", "10", "11", "12", "13", "14","15", "16", "17", "18", "19", "20", "21", "22", "23", "24","25", "26", "27", "28", "29", "30", "31", "32", "33", "31"],
    datasets: [{
      label: "My First dataset",
      fill: false,
      lineTension: 0,
      backgroundColor: "rgba(75,192,192,0.4)",
      borderColor: "rgba(75,192,192,1)",
      borderCapStyle: 'butt',
      borderDash: [],
      borderDashOffset: 0.0,
      borderJoinStyle: 'miter',
      pointBorderColor: "rgba(75,192,192,1)",
      pointBackgroundColor: "#fff",
      pointBorderWidth: 1,
      pointHoverRadius: 5,
      pointHoverBackgroundColor: "rgba(75,192,192,1)",
      pointHoverBorderColor: "rgba(220,220,220,1)",
      pointHoverBorderWidth: 2,
      pointRadius: 4,
      pointHitRadius: 10,
      data: [jArray],
    }]
  };

  var myChart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: {
      "horizontalLine": [{
        "y": 140,
        "style": "rgba(255, 0, 0, .4)",
      }, {
        "y": 120,
        "style": "#00ffff",
      }]
    }
  });

  </script>

这就是图表的外观。它获取第一个数据,然后停止。

感谢任何帮助。 (我只需要一个包含数据库数据的图表,我使用 pdo)

我可以使用$result 获得相同的结果,我在其中获得第一个数据点。像这样

  <?php
  $sth = $db->prepare("SELECT Actual FROM csvhoejde1");
  $sth->execute();

  /* Fetch all of the remaining rows in the result set */
  $result = $sth->fetchAll(PDO::FETCH_COLUMN, 0);
  $result = explode("@", implode(",@", $result));
  // print_r for at se resultaterne.
  echo'<pre>';
  print_r($result);
  echo'</pre>';

?>

脚本:

var jArray = <?php echo json_encode($result); ?>;
for ($i = 0; $i < jArray.length; $i++) { 
...
data: [jArray[$i]],

【问题讨论】:

  • 看来你json_encode()-输入了错误的变量$data,它只用于print_r()结果集,即:$result
  • 我没有从&lt;?php echo json_encode($result); ?&gt;;得到任何数据
  • 那是不可能的——你刚刚展示了变量$result 包含129.74, 130.74, 129.50, 129.10, 129.80, 129.74, 129.90, 129.74...和foreach()。您是否使用不同的文件,不清楚?如果是这样,您需要将$result 的值传递给下一个脚本。
  • 我的意思是$result 里面有数据,但是当我使用&lt;?php echo json_encode($result); ?&gt;; 时,我在图表中没有数据我会添加一张图片,这样你就可以明白我的意思了。
  • 您是否在使用两个不同的文件,一个用于获取$result 中的数据,另一个用于访问和呈现$result 中的数据?

标签: javascript php pdo chart.js


【解决方案1】:
...
$data = [];
// set all data to d.
foreach ($result as $d) {
  $data[] = $d;
}
?>

在chart.js中

var jArray = <?php echo implode(',', $data); ?>

【讨论】:

  • 我使用&lt;pre&gt;&lt;/pre&gt; 来获取print_r($data),以便于阅读。当我使用header('Content-Type: text/plain'); 时,我会以纯文本形式获取我的网站
  • 它得到的结果与$result 在没有任何 foreach 的情况下给出的结果相同
【解决方案2】:

在对其他图表库进行大量研究后,我注意到 highcharts 使用了 echo join() 并让它看起来像这样

这是我的解决方案

<div class="row bg-dark">
    <div class="col-12 border">
    <canvas id="myChart"></canvas>
    </div>
</div>

<div class="container">
  <div>
    <?php
      $sth = $db->prepare("SELECT Actual FROM csvhoejde1");
      $sth->execute();

      /* Fetch all of the remaining rows in the result set */
      $result = $sth->fetchAll(PDO::FETCH_COLUMN, 0);
      // $result = explode("@", implode(",@", $result));
      // print_r for at se resultaterne.
      echo'<pre>';
      print_r($result);
      echo'</pre>';

    ?>
  <div>
</div>
  <!----------------------myChart---------------------->
  <script src="./assets/charts/dist/Chart.js"></script>
<script>



var canvas = document.getElementById("myChart");
var ctx = canvas.getContext("2d");

var horizonalLinePlugin = {
  afterDraw: function(chartInstance) {
    var yScale = chartInstance.scales["y-axis-0"];
    var canvas = chartInstance.chart;
    var ctx = canvas.ctx;
    var index;
    var line;
    var style;

    if (chartInstance.options.horizontalLine) {
      for (index = 0; index < chartInstance.options.horizontalLine.length; index++) {
        line = chartInstance.options.horizontalLine[index];

        if (!line.style) {
          style = "rgba(169,169,169, .6)";
        } else {
          style = line.style;
        }

        if (line.y) {
          yValue = yScale.getPixelForValue(line.y);
        } else {
          yValue = 0;
        }

        ctx.lineWidth = 3;

        if (yValue) {
          ctx.beginPath();
          ctx.moveTo(0, yValue);
          ctx.lineTo(canvas.width, yValue);
          ctx.strokeStyle = style;
          ctx.stroke();
        }

        if (line.text) {
          ctx.fillStyle = style;
          ctx.fillText(line.text, 0, yValue + ctx.lineWidth);
        }
      }
      return;
    };
  }
};
Chart.pluginService.register(horizonalLinePlugin);

var data = {
  labels: ["1", "2", "3", "4", "5", "6", "7","8", "9", "10", "11", "12", "13", "14","15", "16", "17", "18", "19", "20", "21", "22", "23", "24","25", "26", "27", "28", "29", "30", "31", "32", "33", "31"],
  datasets: [{
    label: "My First dataset",
    fill: false,
    lineTension: 0,
    backgroundColor: "rgba(75,192,192,0.4)",
    borderColor: "rgba(75,192,192,1)",
    borderCapStyle: 'butt',
    borderDash: [],
    borderDashOffset: 0.0,
    borderJoinStyle: 'miter',
    pointBorderColor: "rgba(75,192,192,1)",
    pointBackgroundColor: "#fff",
    pointBorderWidth: 1,
    pointHoverRadius: 5,
    pointHoverBackgroundColor: "rgba(75,192,192,1)",
    pointHoverBorderColor: "rgba(220,220,220,1)",
    pointHoverBorderWidth: 2,
    pointRadius: 4,
    pointHitRadius: 10,
    data: [<?php echo join($result, ',') ?>],
  }]
};

var myChart = new Chart(ctx, {
  type: 'line',
  data: data,
  options: {
    "horizontalLine": [{
      "y": 140,
      "style": "rgba(255, 0, 0, .4)",
    }, {
      "y": 120,
      "style": "#00ffff",
    }]
  }
});
</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-21
    • 2023-03-23
    相关资源
    最近更新 更多