0

I have two arrays in PHP which I am trying to pass to a Chart to be displayed in Chartjs.

The following code creates the arrays by using a foreach on a multidimensional array to extract them.

<?php
    $behaviours = orderByType($_SESSION['loggedStudent']['studentID']);
    $behTypes = array();
    $behValues = array();
    foreach($behaviours as $item){
        $behTypes[] = $item["type"];
        $behValues[] = intval($item["count(*)"]);
    }
    // php arrays to JSON
    $behaviourLabels = json_encode($behTypes, TRUE); 
    $behaviourValues = json_encode($behValues, TRUE);
?>

<canvas id="pie-chart" width="800" height="450"></canvas>

<script>
// parse to js
var strLables = <?php echo($behaviourLabels); ?>;
var strValues = <?php echo($behaviourValues); ?>;

// parse as array
var arrLables = JSON.parse($strLables);
var arrValues = JSON.parse($strValues);

new Chart(document.getElementById("pie-chart"), {
    type: 'pie',
    data: {
      labels: arrLabels,
      datasets: [{
        label: "Incident Type",
        backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
        data: arrValues,
      }]
    },
    options: {
      title: {
        display: true,
        text: 'Breakdown of incident types for <?php echo($_SESSION['loggedStudent']['firstName']);  ?>'
      }
    }
});

</script>

No chart or labels are showing. What am I doing wrong?

1 Answer 1

1

The expected values for both data and labels are array.

What you need to do is pass json to JavaScript.

// php arrays to JSON
$behaviourLabels = json_encode($behTypes);
$behaviourValues = json_encode($behValues);

Now in javascript

var arrLables = <?php echo($behaviourLabels); ?>;
var arrValues = <?php echo($behaviourValues); ?>;

// Now use them directly in you configuration
data: {
      labels: arrLables,
      datasets: [{
        label: "Incident Type",
        backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
        data: arrValues,
      }]
    },
Sign up to request clarification or add additional context in comments.

13 Comments

first section was php code not javascript and in second we're passing value from php variable to javascript variable.
oh i'm really sorry that is wrong, i mistakenly did that. Updated my answer. and verify whether you're getting data in strLables and strValues by using console.log(strLables, strValues)
try enclosing them into a double quote.
see this var strLables = "<?php echo($behaviourLabels); ?>"; and its below line. both are now enclosed in double quote. Let me know if it works or not
may be you're getting error due to double quote. Let me give you one more subtle solution. Give me some time
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.