Переменные данных Chart.js, как я могу заставить это работать? - PullRequest
0 голосов
/ 11 февраля 2019

Я пытаюсь использовать переменную php в качестве данных в моем Chart.js, но я просто не могу заставить ее работать.это одна из моих попыток.

Результат print_r($data);

$data = 129,74, 130,74, 129.50, 129.10, 129.80, 129.74, 129.90, 129.74

и мой код (я сократил его, чтобы его было легче читать)

<code><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'
';}?>

И это мой сценарий для моего чарта. 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>

Так выглядит диаграмма.он получает первые данные, но затем останавливается. enter image description here

Любая помощь приветствуется.(мне просто нужна диаграмма с данными из моей базы данных, я использую pdo)

Я могу получить тот же результат с $result, где я получаю первую точку данных.вот так

<code>  <?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'
';?>

Сценарий:

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

Ответы [ 2 ]

0 голосов
/ 11 февраля 2019

После большого количества исследований других библиотек диаграмм я заметил, что старшие графики использовали echo join() и заставил его выглядеть так enter image description here

Вот мое решение

<code><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'
«;?>
0 голосов
/ 11 февраля 2019
...
$data = [];
// set all data to d.
foreach ($result as $d) {
  $data[] = $d;
}
?>

В chart.js

var jArray = <?php echo implode(',', $data); ?>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...