简体   繁体   中英

Display PHP Array in Chart.js tooltip

I have a Bar Chart created with Chart.js. I get the data and labels from PHP Arrays which look like this:

for ($i = 0; $i < count($mydata); $i++) {
    $labels .= "\"".$mylabels[$i] ."\"". ",\n" // "Label 1", "Label 2", "Label 3", ...
    $data .= $mydata[$i] . ",\n" // 34, 12, 64, 12, ...
}

I then create the Chart using this code:

$chart = '
<script>
var data = {
    labels: ['.$labels.'],
    datasets: [
        {
            label: "My First dataset",
            fillColor: "rgba(220,220,220,0.75)",
            strokeColor: "rgba(220,220,220,1)",
            highlightFill: "rgba(221, 240, 242, 1)",
            highlightStroke: "rgba(204, 231, 234, 1)",
            data: ['.$data.']
        }
    ]
};

var ctx = document.getElementById("myChart").getContext("2d");

new Chart(ctx).Bar(data, {
    scaleLabel : "<%= value + \" €\" %>",
    tooltipTemplate: "<%= \"Project: \" + label %>",
});

</script>';
print($chart);

This works fine so far but I need to display an Array inside the respective tooltip. So this line of code needs to be changed:

tooltipTemplate: "<%= \"Project: \" + label %>"

First I tried to display a PHP Variable inside it which looks like this:

tooltipTemplate: "<%= '. $test .' \"Project: \" + label %>"

EDIT: It seems I need to display the variable like this:

tooltipTemplate: " '. $test .'<%= \"Project: \" + label %>"

But how do I loop through an Array to display each element in the respective tooltip?

My code is probably not so clean so I appreciate Tipps and Help from you as I am still learning to write clean code.

tooltips: {
    enabled: true,
    mode: 'single',
    callbacks: 
      {
        title: function(tooltipItem, data) 
        {
            return cpc_label[tooltipItem[0]['index']];
        },
      }
},

cpc_label is my javascript array of tooltip titles. Using this code it makes the array display each element in the respective tooltip.

Hope this solves your issue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM