如何在图表js图表中使用php变量

时间:2017-11-10 08:46:27

标签: javascript php chart.js

我的php应用程序中有以下图表。我想通过php变量加载图表数据。即

<script>
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ['Excellent', 'Good', 'Fair', 'Poor'],
        datasets: [{
            label: 'This Month',
            data: [15, 19, 3, 17],
            backgroundColor: "rgba(153,255,51,0.4)"
        }, {
            label: 'oranges',
            data: [2, 29, 5, 5, 2, 3, 10],
            backgroundColor: "rgba(255,153,0,0.4)"
        }]
    }
});
</script>

所以我正在寻找一种方法让数据部分读取像$ good这样的变量而不是像12这样的原始数字。

1 个答案:

答案 0 :(得分:0)

使用php Join功能

// 1. fictional array defined in PHP
<?php 
    $arr=[15, 19, 3, 17];
    ?>
<script>
var ctx = document.getElementById('myChart').getContext('2d');

// 2. convert the php array into a javascript variable
var dataArray = [<?php echo join(',',$arr); ?>];
var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ['Excellent', 'Good', 'Fair', 'Poor'],
        datasets: [{
            label: 'This Month',
            data: dataArray, // 3. use the javascript variable here.
            backgroundColor: "rgba(153,255,51,0.4)"
        }, {
            label: 'oranges',
            data: [2, 29, 5, 5, 2, 3, 10],
            backgroundColor: "rgba(255,153,0,0.4)"
        }]
    }
});
</script>