Chartjs-Display php array data in chart.js javascript

0๐Ÿ‘

โœ…

You need to supply the labels and data separately. You could create two variables in your loop for this:

$chatLabels = []; 
$chatData = [];
while ($userchat= mysqli_fetch_array($rscht)) {
      $chatLabels[] = $userchat['name'];
      $chatData[] = $userchat['times'];
}
$chatLabelsJson = json_encode($chatLabels); // ["John Mark","Sandra Friday","Kelvin Russel"]
$chatDataJson = json_encode($chatData); //["25","12","4"]

Alternatively you could use array_column to pull out the data from your existing $chatstack array:

$chatLabels = array_column($chatstack, 'label');
$chatData = array_column($chatstack, 'value');
$chatLabelsJson = json_encode($chatLabels); // ["John Mark","Sandra Friday","Kelvin Russel"]
$chatDataJson = json_encode($chatData); //["25","12","4"]

0๐Ÿ‘

So PHP is a backend server side technology, JS in this context is a client side only context. PHP will allow you to print this json encoded data into a script block that will allow you to assign this data to a JS variable.

Alternatively you could use a cookie to store this data and read it from there.

Leave a comment