Display array inside the chartjs

Asked

Viewed 37 times

1

I wonder if you could help me with the following situation:

I have a column called event type , in it after completing a form will be inserted some of the 4 items: Collision, PT, THEFT, Theft.

I’m wanting to make a query and know how many times each of the items appears in the column and display them in graph using chartjs.

Follows code below:


    public function contar2()
    {
        try {
            $query = $this->bd->prepare("SELECT tipo_evento, COUNT(tipo_evento) AS Quantidade FROM vistorias GROUP BY tipo_evento HAVING COUNT(tipo_evento) > 1 ORDER BY COUNT(tipo_evento) DESC");
            $contar_dados = array($_GET['tipo_evento']);
            $query->execute(array($contar_dados));
            $conta = $query->rowCount();

            if ($conta > 0) {
                $query->fetch(PDO::FETCH_ASSOC);
            }
        } catch (PDOException $e) {
            die($e->getMessage());
        }
        return $query->fetchAll();
    }

On the page where I want to display the items, I am calling the function as follows:

   $contar2 = $acoes->contar2();
   $furto = $contar2[2]['tipo_evento'];
   $furto2 = $contar[2]['Quantidade'];

I put the command below on the page and returned me the array as follows:

    echo '<pre>';
print_r($cliente);
echo '</pre>';
[
{
0: {
0: "Colisão",
1: "4",
tipo_evento: "Colisão",
Quantidade: "4"
},
1: {
0: "PT",
1: "3",
tipo_evento: "PT",
Quantidade: "3"
},
2: {
0: "Furto",
1: "3",
tipo_evento: "Furto",
Quantidade: "3"
},
3: {
0: "Opcionais",
1: "2",
tipo_evento: "Opcionais",
Quantidade: "2"
}
},
"</pre>",

You could take this information from the array and insert it into the chartjs chart ?

I can even catch them if I do:

$furto = $contar2[2]['Quantidade'];
echo "Meu Array possui: ".$furto2.' elementos';

This way, it returns me how many times it was displayed, but I can not put inside the chartjs...

Thanks in advance !

  • Oops, I think the easiest way is to turn this into json and move it to your msm frontend, either using ajax requests or creating javascript object with php when displaying your page type <script> var obj = <?php echo json_encode($seu_array) ?> </script>

  • @andre_luiss - Yeah, I’m sorry the ignorance, but I didn’t understand how I could call the values inside the graph, I could exemplify a little more for kindness

  • Because it is chartJS you have to send an array to it, but it is up to you to format this array to fit the chart and make sense. If Voce has $array = ['fruta' => 'banana'], using json_encode the output of the array would be a string {"fruta":"banana"}, so you are already able to manipulate via javascript

1 answer

0


After a few attempts, I managed to solve my problem as follows, I will post here if help someone in the future.

I created a file named app.js with the following code:

$('document').ready(function () {
    $.ajax({
        type: "POST",
        url: "chart.php",
        dataType: "json",
        success: function (data) {

            var nomearray = [];
            var vendasarray = [];
            for (var i = 0; i < data.length; i++) {

                nomearray.push(data[i].tipo_evento);
                vendasarray.push(data[i].Quantidade);

            }
            grafico(nomearray, vendasarray);
        }

    });
})

function grafico(nome, vendas) {
    var ctx = document.getElementById('myChart').getContext('2d');
    var myDoughnutChart = new Chart(ctx, {
        // The type of chart we want to create
        type: 'doughnut',
        // The data for our dataset
        data: {
            labels: nome,
            datasets: [{
                label: 'My First dataset',
                backgroundColor: ['#f56954', '#00a65a', '#f39c12', '#00c0ef', '#3c8dbc', '#d2d6de'],
                data: vendas
            }]
        },

        // Configuration options go here
        options: {}
    });

}

Then I created a file called Chart.php to send the data, with the following code:

<?php

$pdo = new PDO('mysql:host=localhost;dbname=NOMEDATABELA;port=3306;charset=utf8', 'usuario', 'senha');

$sql = "SELECT tipo_evento, COUNT(tipo_evento) AS Quantidade FROM vistorias GROUP BY tipo_evento HAVING COUNT(tipo_evento) > 1 ORDER BY COUNT(tipo_evento) DESC";

$statement = $pdo->prepare($sql);

$statement->execute();


while($results = $statement->fetch(PDO::FETCH_ASSOC)) {

    $result[] = $results;
}

echo json_encode($result);

Browser other questions tagged

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