Generate CSV with side-by-side results in PHP

3

I'm trying to get comparative results in a CSV generated in php but I can not stack side by side in the way it illustrates EXPECTED OUTPUT attached image.

I made a code below that did not break the line when it changes to 2018

TABLE

CREATE TABLE 'clientes_vendas' (
  'codigo' int(11) NOT NULL,
  'cliente_cnpj' varchar(40) NOT NULL,
  'codigo_cliente' int(11) NOT NULL,
  'codigo_repre' int(11) NOT NULL,
  'valor' decimal(10,2) NOT NULL DEFAULT '0.00',
  'dia' varchar(20) NOT NULL,
  'mes' varchar(40) NOT NULL,
  'ano' varchar(40) NOT NULL,
  'data' date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CODE

while:                         

  if ($ano_atual2==0) {
      $ano_atual2 = $ano;
  }  
  $pula_linha="\n";

  if ( $ano != $ano_atual2 )  :
      $ano_atual2 = $ano;
      $dadosTXT2 = "$pula_linha$nome_repre;$mes;$ano$pula_linha";
      $arraDados[] = $dadosTXT2;
      $soma=0;
  endif;

   @$soma +=  $row['valor'];
   $somaConvert = number_format($soma,2,",",".");
   $dadosTXT2 = "$cnpj_cliente;$nome_cliente;$nome_repre;$mes;$ano;$valor$pula_linha";
   $arraDados[] = $dadosTXT2;

endwhile; 

$fp = fopen($csv, 'a');
$escreve1 = fwrite($fp,   utf8_decode($header));

foreach ($arraDados as $file) {
    $escreve2 = fwrite($fp,  $file);
}

fclose($fp);

EXPECTED OUTCOME: Display SUMS of customer sales side by side EXAMPLE: AUGUST 2017, AUGUST 2018, SEPTEMBER 2017- SEPTEMBER 2018 but usually beginning in January

    
asked by anonymous 23.04.2018 / 22:17

2 answers

3

To answer your question I had to create other tables that were not informed to get nome_representante and nome_cliente . And for testing I've created a few miscellaneous records, see:

Asanoption,Iusedtheinputvalueatthebeginningoftheyearandattheendoftheyeartobeanalyzed,becauseyoumightwanttomakeafilter.Seethelinebelow:

$anoInicio="2017";
$anoFim = "2018";

Finally, I created the code based on yours. Notice that select is sorting, first by month, then by customer code, and then by year. This way you will get the expected result.

    $anoInicio = "2017";
    $anoFim = "2018";

    $query = mysqli_query($conn, "SELECT ano, mes, 
        (
            SELECT nome_cliente FROM cliente 
            WHERE cliente.codigo_cliente = clientes_vendas.codigo_cliente 
        ) AS 'nome_cliente', 
        (
            SELECT nome_representante FROM representante 
            WHERE representante.codigo_representante = clientes_vendas.codigo_representante 
            GROUP BY representante.codigo_representante
        ) AS 'nome_representante', 
        SUM(valor) AS 'total' FROM clientes_vendas 
        WHERE ano >= '$anoInicio' AND ano <= '$anoFim' 
        GROUP BY mes, codigo_cliente, ano ORDER BY codigo_cliente, mes, ano ASC"
        );

    $arraDados = array();
    $strTmpCliente = "";
    $mes = array('', 'Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'); // formatador dos meses
    $x = 1;


    while($dados = mysqli_fetch_assoc($query)){

        if($strTmpCliente != $dados['nome_cliente']){
            $strTmpCliente = $dados['nome_cliente'];
            $arraDados[$strTmpCliente] = array();
            $arraDados[$strTmpCliente]['nome'] = $dados['nome_cliente'];
            $arraDados[$strTmpCliente]['representante'] = $dados['nome_representante'];
        }

        $strMesAno = $mes[$dados['mes']]."_".$dados['ano'];
        $arraDados[$strTmpCliente][$strMesAno] = number_format($dados['total'],2,",",".");

    }


    $header = "Cliente;Representante;";
    $mesAtual = 1;
    $anoAtual = (int)$anoInicio;

    $arrayDatas = array();

    for($x = 0; $x < 24; $x++){

        $data = $mes[$mesAtual]."_".$anoAtual;
        $arrayDatas[] = $data;
        $header .= str_replace("_", "'",$data).";";

        $alteraMes = $x % 2 == 0 ? false : true;
        if($alteraMes){
            $mesAtual++;
            $anoAtual = $anoInicio;
            continue;
        }
        $anoAtual = $anoFim;
    }
    $header = substr($header, 0, -1);
    $header .= "\n";

    $strDados = array();

    foreach($arraDados as $cliente ){

        $strTmp = $cliente['nome'].";".$cliente['representante'].";";
        for($i = 0; $i < count($arrayDatas); $i++){
            $data = $arrayDatas[$i];
            if(isset($cliente[$data])){
                $strTmp .= $cliente[$data].";";
                continue;
            }
            $strTmp .= "-;";
        }

        $strTmp = substr($strTmp, 0, -1);
        $strTmp .= "\n";
        $strDados[] = $strTmp;

    }

    $csv = "arquivo.csv";

    // escreve o cabeçalho
    $fp1 = fopen($csv, 'w');
    fwrite($fp1, $header);
    fclose($fp1);

    // escreve o resultado
    $fp2 = fopen($csv, 'a');
    foreach ($strDados as $file) {
        fwrite($fp2,  $file);
    }
    fclose($fp2);

The generated file looks like this:

EDIT

Inoticedthatin image that you posted that a few months went without sales . I went to do the test in my code and, as I imagined, it made an error. For the values were filled in sequentially.

I've changed the code and is now working properly. I was able to enter the number_format you are using. The result was this:

EDIT2

Changethispartthatwillwork:

if($strTmpCliente!=$dados['nome_cliente']){$strTmpCliente=$dados['nome_cliente'];$arraDados[$strTmpCliente]=array();$arraDados[$strTmpCliente]['nome']=$dados['nome_cliente'];$arraDados[$strTmpCliente]['representante']=$dados['nome_representante'];}//--->oerroestavaaqui$dadosMes=(int)$dados['mes'];//aquieletransformaeminteiro$strMesAno=$mes[$dadosMes]."_".$dados['ano']; // aqui ele grava a strinmg corretamente
            $arraDados[$strTmpCliente][$strMesAno] = number_format($dados['total'],2,",",".");
    
26.04.2018 / 21:21
4
$codigo_cliente = 0;
$pula_linha="\n";
while:                         

  if ($ano_atual2==0) {
      $ano_atual2 = $ano;
  }
  if ( $ano != $ano_atual2 )  :
      $ano_atual2 = $ano;
      $dadosTXT2 = "$pula_linha$nome_repre;$mes;$ano$pula_linha";
      $arraDados[] = $dadosTXT2;
      $soma=0;
  endif;

  if ($codigo_cliente == 0) {
      $codigo_cliente  = $row['codigo'];
      $linha = "$cnpj_cliente;$nome_cliente;$nome_repre;";
  }

  @$soma +=  $row['valor'];
   $somaConvert = number_format($soma,2,",",".");

  if ( $row['codigo']!= $codigo_cliente)  {
       $codigo_cliente  = $row['codigo'];
       $linha .= $pula_linha;
       $arraDados[] = $linha;
       $linha = "$cnpj_cliente;$nome_cliente;$nome_repre;$mes;$ano;$valor";
  }
  else{
    $linha .= "$mes;$ano;$valor;";
  }

endwhile; 

$fp = fopen($csv, 'a');
$escreve1 = fwrite($fp,   utf8_decode($header));

foreach ($arraDados as $file) {
    $escreve2 = fwrite($fp,  $file);
}

fclose($fp);

I hope I have helped or at least come close.

    
26.04.2018 / 05:55