kasiulks
kasiulks

Reputation: 31

Php array and chartjs

i need help with chart.js (www.chartjs.or).

I've got an array in php, lets say

    $array_with_data = array(1,1,1,1,1,1,2,1,2);

this array is from mysql database. And now I want to use this chart.js, where in this line

      data: [12, 19, 3, 5, 2, 3, 2,3,1,2,4,5],

i want replace this array data with my array in php. How can I do this? :) The full code of this chart is at the bottom.

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.js"></script>
<script>
    var myChart = new Chart(ctx, {...});
</script>


<canvas id="myChart" width="400" height="400"></canvas>
<script>



	
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange", "Orange", "Orange", "Orange", "Orange", "Orange", "Orange"],
        datasets: [{
            label: '# of Votes',
		
            data: [12, 19, 3, 5, 2, 3, 2,3,1,2,4,5],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255,99,132,1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        }
    }
});
</script>

Upvotes: 3

Views: 6161

Answers (1)

Arun Kumaresh
Arun Kumaresh

Reputation: 6311

In php

$data = json_encode($array_with_data);

In your js

var data = <?php echo $data ?>;

Upvotes: 5

Related Questions