JavaScript - 将PHP多维数组插入Google Charts中的Javascript类

时间:2022-06-26 21:30:36

I'm using this Google Charts tutorial on how to convert an array into a graph.

我正在使用此Google图表教程,介绍如何将数组转换为图形。

The data in the tutorial is already in the function. Now I want to insert my own data into the function from a PHP array. I managed to convert my PHP array into a JavaScript array. Below is my code:

本教程中的数据已经在函数中。现在我想从PHP数组中将自己的数据插入到函数中。我设法将我的PHP数组转换为JavaScript数组。以下是我的代码:

$jsArray = array();
foreach($movingAverages as $movingAverage) {
   $jsArray[] = array((int) $movingAverage['unix'], (int) $movingAverage['closing-prices']); 
}

Below is my sample code:

以下是我的示例代码:

Array
(
    [0] => Array
        (
            [0] => 1505040240
            [1] => 3452
        )

    [1] => Array
        (
            [0] => 1505040300
            [1] => 3451
        )

    [2] => Array
        (
            [0] => 1505040360
            [1] => 3446
        )

    [3] => Array
        (
            [0] => 1505040420
            [1] => 3449
        )

This is my current Javascript Code:

这是我目前的Javascript代码:

    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">

    var js_array = <?php echo json_encode($jsArray);?>;
    alert(js_array);


      google.charts.load('current', {'packages':['corechart']});
      google.charts.setOnLoadCallback(drawChart);

      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['Time', 'Closing Prices'],
        [js_array]


        ]);

        var options = {
          title: 'BTC-EUR',
          curveType: 'function',
          legend: { position: 'top' }
        };

        var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));

        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <div id="curve_chart" style="width: 100%; height: 500px"></div>
  </body>
</html>

When I call alert(js_array); The array is called.

当我呼叫警报(js_array);该数组被调用。

I don't know why the chart is not being displayed. I'm not sure how to insert the js_array into my function drawChart(). This is the first time I'm using JavaScript. So thank you for your help.

我不知道为什么没有显示图表。我不确定如何将js_array插入到我的函数drawChart()中。这是我第一次使用JavaScript。谢谢你的帮助。

1 个解决方案

#1


2  

You're likely adding one more dimension to the array.

您可能会在阵列中再添加一个维度。

var data = google.visualization.arrayToDataTable([
    ['Time', 'Closing Prices'],
    js_array
]);

UPDATE:

js_array.unshift(['Time', 'Closing Prices']);
var data = google.visualization.arrayToDataTable(js_array);

#1


2  

You're likely adding one more dimension to the array.

您可能会在阵列中再添加一个维度。

var data = google.visualization.arrayToDataTable([
    ['Time', 'Closing Prices'],
    js_array
]);

UPDATE:

js_array.unshift(['Time', 'Closing Prices']);
var data = google.visualization.arrayToDataTable(js_array);