How to insert php array values into chart.js line chart?

by giovanny.lueilwitz , in category: Javascript , 8 months ago

How to insert php array values into chart.js line chart?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lily , 8 months ago

@giovanny.lueilwitz 

To insert PHP array values into a Chart.js line chart, you will need to do the following steps:

  1. Create a canvas element in your HTML file where the line chart will be displayed. Give it an id so that you can refer to it later in your JavaScript code.
1
<canvas id="lineChart"></canvas>


  1. Add the necessary script tag to include the Chart.js library to your HTML file.
1
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>


  1. Fetch the PHP array values using AJAX or by directly including the PHP code in your HTML file.
  2. Convert the PHP array values into a JavaScript array using json_encode() function.
1
2
3
4
5
6
<?php
$phpArray = ["value1", "value2", "value3"]; // Replace with your PHP array

$jsArray = json_encode($phpArray);
?>


  1. Create a JavaScript variable and assign the converted PHP array values to it.
1
2
3
<script>
var jsArray = <?php echo $jsArray; ?>;
</script>


  1. Initialize the Chart.js line chart using the JavaScript array.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<script>
var ctx = document.getElementById('lineChart').getContext('2d');
var lineChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ['Label1', 'Label2', 'Label3'], // Replace with your labels
        datasets: [{
            label: 'My Line Chart',
            data: jsArray,
            backgroundColor: 'rgba(255, 99, 132, 0.2)', // Replace with your desired colors
            borderColor: 'rgba(255, 99, 132, 1)', // Replace with your desired colors
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            y: {
                beginAtZero: true
            }
        }
    }
});
</script>


Note: Make sure to replace the labels array with the appropriate labels for your data. Also, modify the data property to use your JavaScript array variable (jsArray) instead of the sample array shown above.


This will create a line chart using Chart.js with the values from your PHP array.