How to chart with Google Charts and PHP

Asked

Viewed 3,488 times

1

inserir a descrição da imagem aquiI need to make a chart where it shows total 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 consultation I can assemble the chart the way I need to? How do I put this data in the graphic montage?

  • can show the structure of your array? with the data. after filling

  • I’m sorry, I don’t understand?

  • you just want to know the way you need the data to mount the chart and how you put this data in javascript to mount the chart?

  • I gave an Edit with an image of the query result. I need to create a chart where there are two columns 'Output' with Totaloutput and the column 'Input' with Totalinput, I don’t know if you have how to do this with this query? If yes, where should I put this data? Because the way I did it didn’t work: array('v' => (int)$obj->Output), array('v' => (int)$obj->Total output), I have no idea how to do this

  • columns? but not pie chart?

  • I meant subtitles, it’s pizza yes, sorry

Show 2 more comments

1 answer

2


With this query I can assemble the chart the way I need?

Google’s pizza chart gets this date format to be generated:

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

i.e., an array of arrays where the first item of the array in the array is the name of the metric ex (Task), and the second is the value (which it occupied in the graph)

See a functional example:

<html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="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>

inserir a descrição da imagem aqui

That is in the first item of array is the title "Entries" and the second value 500

How do I put this data in the graphic montage?

First let’s leave your chart in the structure that google Harts 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 of your array $grafico will look like this:

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

As your photo shows. It is obvious that now you will need to elaborate a logic so that when sending this array to your html with this code:

echo json_encode($grafico);

It mounts the graph correctly. can be based on the functional example of this question.

Browser other questions tagged

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