Problem when displaying array

Asked

Viewed 110 times

-1

I have a problem in logic to display data from an array.

Is the following:

I have a function, which returns the result of entries per UF per day. In it I step 2 parameters, an array with the dates and an array with the states.

Setting the parameters to pass to the function.

$uf = array('sp','rj');

$d1 = '2015-09-15';
$d2 = '2015-09-17';
$timestamp1 = strtotime( $d1 );
$timestamp2 = strtotime( $d2 );

while ( $timestamp1 <= $timestamp2 ) {
   $data_mod[] = date( 'Y-m-d', $timestamp1 ) . PHP_EOL; // data_mod vira um array com as data entre $d1 e $d2
   $timestamp1 += 86400;
}

Function:

function grafico_cadastro_por_dia($conexao,$uf,$data_mod){
$lista = array();
$qtd_dias = count($data_mod);
$qtd_uf = count($uf);

for($i = 0; $i <= $qtd_uf; $i++) {
if( $uf[$i] ) {  $where[] = " uf = '{$uf[$i]}'"; } //monto o implode para o array de UF
}

for($i = 0; $i <= $qtd_dias; $i++) {
if( $data_mod[$i] ) {  $where2[] = " dataCadastro = '{$data_mod[$i]}'"; } //monto o implode para o array de datas
} 

$query = "SELECT dataCadastro,uf,sum(cadastros) FROM tblCadastros where (".implode( ' or ',$where2 ).") AND (".implode( ' or ',$where ).") group by 1,2";
   $sql = mysql_query($query,$conexao);
   while($row = mysql_fetch_assoc($sql)){
   $lista[] = $row;
 } 
return $lista;
}

On return of function, I receive the following data.

$funcao = grafico_cadastro_por_dia($conexao,$uf,$data_mod);

for($i = 0; $i <= count($funcao); $i++){
  echo  '<br>';
 print_r($funcao[$i]);
}

Resultado: 

Array ( [dataCadastro] => 2015-09-15 [uf] => SP [sum(cadastros)] => 36 )
Array ( [dataCadastro] => 2015-09-15 [uf] => RJ [sum(cadastros)] => 9 )
Array ( [dataCadastro] => 2015-09-16 [uf] => SP [sum(cadastros)] => 19 )
Array ( [dataCadastro] => 2015-09-16 [uf] => RJ [sum(cadastros)] => 8 )
Array ( [dataCadastro] => 2015-09-17 [uf] => SP [sum(cadastros)] => 14 )
Array ( [dataCadastro] => 2015-09-17 [uf] => rj [sum(cadastros)] => 2 )

As you can see , the function returns 2 times the date because it has more than one state to display the value.

If I pass 3 states in the array, it would display 3 times the same date.

So far, so good.

The problem starts now, since I will put these results on a graph.

And I’m having trouble printing the results in the order the graph asks for.

You’d have to exhibit in that order:

[$data, $total "uf SP" , $total "uf RJ"]
['2015-09-15', 36 , 9],// 36 é o valor de cadastro de SP no dia 15 e 9 o valor de cadastros de RJ no dia 15
['2015-09-16', 19 , 8],

and so on.

But I’ve sketched out all the ways I can imagine, but I couldn’t display the data that way.

Can someone help me?

  • 1

    Henrique, I re-read it three times, I’m sorry. Maybe it’s the tiredness but I couldn’t absorb your doubt. I understood the structure of the array but did not understand how the output should be. Please put more code, you just said the structure of the array but I believe I’m missing little code, and be specific in the output you want. Well, I’m sorry again.

  • Do these dates come from the database? Or simply from an array()?

  • As I am testing in host place , I am setting the dates manually , but when pass to the server I will receive them via POST. @juniorb2ss , then , the rest of the code would be my function that picks up the data in the database.

  • Giving a print_r in the function, it returns : Array ( [0] => Array ( [dataCadastro] => 2015-09-15 [Uf] => SP [sum(total)] => 36 ) [1] => Array ( [dataCadastro] => 2015-09-15 [Uf] => RJ [sum(total)] => 9 ) [2] => Array ( [dataCadastro] => 2015-09-16 [Uf] => SP [sum(total)] => 19 ) [3] => Array ( [dataCadastro] => 2015-09-16 [Uf] => RJ [sum(total)] => 8 ) [4] => Array ( [dataCadastro] => 2015-09-17 [Uf] => SP [sum(total)] => 14 ) [5] => Array ( [dataCadastro] => 2015-09-17 [Uf] => Rj [sum(total)] => 2 ) ).

  • Friend, it has bad formatting of this your array. It is formatted incorrect, I will try to post a reply.

  • Which graphic library are you trying to use? Have an online example? For ease of reading, you could work with a nested matrix by interest, EX: ['2015-09-15' => ['SP' => 10, 'RJ' => 15], '2015-09-16' => ['SP' => 3, 'RJ' => 11]]

  • 1

    There is a problem in logic itself. I believe that the way you are doing is not very indicated, another detail, is that you can get by the alias: sum(cadastros) as total_cadastros : $row["total_cadastros"]. This output you are doing, can be done directly in the query.

  • Good afternoon, I use Google Maps. I am putting together a graphic of lines, to know the days that had more entries on the site.

Show 3 more comments

1 answer

1


You are going through many arrays to at the end assemble a query to get the values by date of the entries made in that UF, and own SQL tools for this.

We have the function Between which is used for comparisons.

In this example I will show how to take all records made between a date period and group by the registration date and Uf.

So I can return all entries made in x UF for Y day, mounting array you need.

In this query I will use the DATE_FORMAT Mysql, because I’m going to assume that your field dataCadastro have the registration time, if I do not format this date I will group the registrations by dia/mês/ano hora:minuto:segundo which is not what you need, you need just by dia/mês/ano.

Just run this query instead of all this code:

SELECT 
DATE_FORMAT(`dataCadastro`, '%Y-%m-%d') AS `dataCadastro`,
uf,
SUM(cadastros) AS 'Cadastros'
FROM
  tblCadastros
WHERE
  dataCadastro BETWEEN 2015 - 09 - 15 AND 2015 - 09 - 17
GROUP BY DATE_FORMAT(`dataCadastro`, '%Y-%m-%d'), `uf`

Just run this query instead of all this code you did. The result of this you can mount a dynamic array more or less like this:

Array
(
    [2015-09-15] => Array
    (
        [SP] => 36
        [RJ] => 9
    )
)

Look at the ideone

How final:

$query = 'SELECT DATE_FORMAT(`dataCadastro`, "%Y%m%d") as `dataCadastro`, uf, sum(cadastros) as Cadastros FROM tblCadastros where dataCadastro BETWEEN '. $d1 .' and '. $d2 .' GROUP BY `dataCadastro`, `uf`';
$sql = mysql_query($query,$conexao);

while($row = mysql_fetch_assoc($sql))
{
    $lista[$row['dataCadastro']] = [
        $row['uf'] => $row['Cadastros']
    ];
} 

Doubts? See how you’ve reduced all that code?

That way you have an array mounted with the information you want to mount the graph, then just go through it.

Edit

$lista = array();

while($row = mysql_fetch_assoc($sql))
{
   if(!isset($lista[$row['dataCadastro']]))
   {
    $lista[$row['dataCadastro']] = array(
        $row['uf'] => $row['Cadastros']
    );
   }
   else
   {
      $lista[$row['dataCadastro']] += array(
        $row['uf'] => $row['Cadastros']
      );
   }
} 

See in operation

  • Thanks for your help. But , gave the following error : Parse error: syntax error, Unexpected '[' in F: INSTALLED PROGRAMS Ampps www tests teste_loop loop_data_uf index.php on line 63. Contents of line 63 : $list[$Row['dataCadastro']] = [ $Row['Uf'] => $Row['Entries'] ]; From now on, grateful

  • 1

    Henrique, this is a syntax error. Just correct friend. Which version of your PHP? It is not supported to open array like this [] where you have to trade for array()

  • junior , thanks again for the help. It’s in version 5.3 if I’m not mistaken. I tried it like this: $list = array("data_register" => $Row['dataCadastro'],"data" => array( "Uf" => $Row['Uf'],"entries" => $Row['entries']); . But when giving a print_r on the return , it only showed a line.

  • Because you’re overwriting the array, Henrique. See my updated response.

  • @Henriquefelix see the edition of the reply.

  • almost . Gave this output : Array ( [2015-09-15] => Array ( [SP] => 36 ) [2015-09-16] => Array ( [SP] => 19 ) [2015-09-17] => Array ( [SP] => 14 ) . In the case , did not catch the other state .

  • Henry, please analyze the code. We can’t just give away. Please signal the answer as correct and Positive, with small adjustments you make the array you need.

  • Junior, it worked. I hadn’t seen his last Edit. Return: Array ( [2015-09-15] => Array ( [RJ] => 9 [SP] => 36 ). Thank you very much for your patience and help.

  • The important thing is not only to work, is to study the query, look at the difference between running a query than 30 lines of code that was your code, study the functions used, @Henriquefelix

  • I noticed. What weighed was the time to compare the date, I don’t know why I did it like that, and betwen would solve it ,making Cod more correct.Now, I’m going to take a closer look at the array, because I lost a bit of how you did it. Once again, thank you.

Show 5 more comments

Browser other questions tagged

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