How to assemble chart with Google charts and PHP

0

I need to make a graph where it shows the total of entries and exits in pizza, I tried something like:

<?php

//Estrutura básica do gráfico

$grafico = array(
    'dados' => array(
        'cols' => array(
        ),
        'rows' => array()
    ),
);

//Consulta dados no BD
$pdo = new PDO('mysql:host=localhost;dbname=despesas', 'root', '');
$sql = 'select 'Saidas',SUM(contas.valor) as TotalSaidas
from contas
union
select 'Entradas',SUM(contas_receber.valor) as TotalEntradas
from contas_receber';
$stmt = $pdo->query($sql);
while ($obj = $stmt->fetchObject()){
    $grafico['dados']['rows'][] = array('c' => array(
        array('v' => (int)$obj->Saidas),
        array('v' => (int)$obj->TotalSaidas),
    ));
}

// Enviar dados na forma de JSON
header('Content-Type: application/json; charset=UTF-8');
echo json_encode($grafico);
exit(0);

With this query I can assemble the chart the way I need? How do I put these data into the chart assembly?

    
asked by anonymous 07.02.2018 / 18:35

1 answer

0
  

With this query, can I assemble the graph the way I need it?

The Google pie chart receives this date format to be generated:

[
   ['Task', 'Hours per Day'],
   ['Entradas',  500],
   ['Saidas',    1100]
]

that is, an array of arrays where the first array item in the array is the name of the metric ex (Task), and the second is the value (which it will occupy in the graph)

See a working example:

<html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script><scripttype="text/javascript">
      google.charts.load('current', {'packages':['corechart']});
      google.charts.setOnLoadCallback(drawChart);

      function drawChart() {

        var data = google.visualization.arrayToDataTable([
          ['Task', 'Hours per Day'],
          ['Entradas',  500],
          ['Saidas',    1100]
        ]);

        var options = {
          title: 'My Daily Activities'
        };

        var chart = new google.visualization.PieChart(document.getElementById('piechart'));

        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <div id="piechart" style="width: 900px; height: 500px;"></div>
  </body>
</html>

Thatis,inthefirstitemofarrayisthetitle"Entries" and the second the value 500

  

How do I put these data into the chart assembly?

First let's leave your graphic in the structure that google charts asks for pizza:

$grafico = [
             ['Task', 'Hours per Day']
           ];
//aonde esse primeiro array com esse elemento é o que está pedindo no [site][2]

Then you need to insert the result in the right places to generate the array as expected.

//crio um array auxiliar
$array_auxiliar = [];

//esse while irá retornar duas linhas (conforme sua foto)
while ($obj = $stmt->fetchObject()){

    //coloco o titulo para saidas (que na sua foto representa o texto)
    $array_auxiliar[0] = $obj->Saidas;
    //coloco o valor para saidas (que na sua foto representa o valor)
    $array_auxiliar[1] = (int)$obj->TotalSaidas;

    //adiciono em gráfico o array com os dados e o titulo saida.
    $grafico[] =  $array_auxiliar;

}

At the end your array $grafico will look like this:

[
   ['Task', 'Hours per Day'],      
   ['Saidas',    1100],
   ['Entradas',  500]
]

As your picture shows. Of course now you need to work out a logic so that by sending this array to your html with this code:

echo json_encode($grafico);

It assembles the chart correctly. can be based on the functional example of this question.

    
07.02.2018 / 19:30