Dar Foreach label on Chartjs / Canvas - Codeigniter

Asked

Viewed 284 times

0

I have a problem here, which may be simple, I don’t know I’m using a frame for the chart, where I can put the boxes I want so that it will be displayed at each bar. Getting like this:

Cada item (Janeiro, Fevereiro, Março... corresponde a uma label no seguinte código

Each item (January, February, March... corresponds to a label in the following code:

var data = {
    labels: ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"],

I’m wanting to bring these labels by the database I use, and even do it normally, and display the array normally. However, I am trying the following code:

var data = {
            labels: ["<?php foreach ($fase as $fase){ echo $fase->nomefase;} ?>"],
            datasets: [

The problem with this code is that I cannot insert a comma to separate the items from the array that I search from the database. At the time of entering the comma, the foreach ends, and starts again, causing it to display no item, or if I have only one item on array, it displays the first and only.

I tried to break into fragments several times and tried so hard to make it work, but it gives error.

  • 1

    That seems wrong: foreach ($fase as $fase) wouldn’t be something like foreach ($phases as $phase)`

  • No no.. the foreach is coming back all right.. I just repeated the variable name there by custom, but it could be $phases the $phase that would give same error

  • Have you ever tried it like this: Labels: ["<? php echo implode("," $phase); ?>"] ?

  • I tried, and did not give.. the chart nor appears haha :/

2 answers

3


Instead of creating the javascript array structure in your hand, let it json_encode() do this for you. Just create the list of names and let the function print the formatted array:

labels: <?php foreach ($fase as $f) { $labels[] = $f->nomefase; } echo json_encode( $labels );  ?>,
  • 1

    Man, it worked perfectly! Thank you so much.

0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.