Calculate average as total of a "cell" in php

1

I need to make a calculation based on the result that I get from the query where it has only split the total value of a person by the average that was obtained from everyone. See the image:

Idonotknowifitwillhelp,butpartofthecodelookslikethis:

$idservico=0;$idservicoAnterior=-1;$totalAtendimentos=0;$quantidadePessoas=0;$media=0;if(empty($mes)||empty($ano)){echo"<script> alert('Favor preencha todos os campos.')</script>";
}else{

    if (isset($hostp))
    {
        $resulta = pg_fetch_array($consulta);
    } else {
        $resulta = $consulta->fetch_array();
    }
while ($resulta) {

    $idservico = $resulta['id_serv'];

    $media = @round($totalAtendimentos / $quantidadePessoas);

    if($idservico != $idservicoAnterior)
    {   
        if($idservicoAnterior != -1)
        {

            echo "<tr>
                    <td style='width: 200px; background-color: #D3D3D3;'></td>
                    <td style='background-color: #D3D3D3;'>Média</td>
                    <td style='background-color: #D3D3D3;'>$media</td>
                    <td style='background-color: #D3D3D3;'></td>
                  </tr>
                </table> <br/>";
        }

        $totalAtendimentos = 0;
        $quantidadePessoas = 0;

        echo "<table border=1>
              <tr style='background-color: #D3D3D3;'>
                <td>Setor</td>
                <td>{$resulta['nm_serv']}</td>
                <td>Total Atendimentos</td>
                <td>Percentual x Média</td>
              </tr>";
    }

    $totalAtendimentos += $resulta['total'];
    $quantidadePessoas += 1;
    $idservicoAnterior = $idservico;

    echo "<tr>
            <td>{$resulta['desc_serv']}</td>
            <td>{$resulta['nm_usu']}</td>
            <td>{$resulta['total']}</td>
            <td>O VALOR DO CÁLCULO VEM AQUI</td>

          </tr>";

I know the code style is not right, but I'm still learning. If you need more information I am available to help you to be helped.

    
asked by anonymous 13.05.2014 / 19:06

2 answers

3

You have missed the most important part of your code that is the structure of the matrix, but even without it, I can give you a mathematical orientation on how to do it.

From your table heading you want to show the percentage of each person's attendance (I imagine). Mathematically speaking, you solve this with the old cross-multiplication:

A --- B
C --- D

Being:

Total de Atendimentos  --- 100%

Atendimentos da Pessoa --- X

Placing the sketch above in a mathematical formula, we have:

D = BC / A

Being:

  • A Total Calls
  • B the total percentage (always 100)
  • C the number of calls from the person in question
  • D the value of the equation you need to find out

Applying the numbers in the formula we have, for the first person (322 calls):

D = ( 100 * 322 ) / 354
D = 32200 / 354
D = 90,96%

You can create a function that takes three values and returns the result to be shown where you need it in that table cell;

function getPercentage( $total, $attendances ) {
    return round( ( 100 * $attendances ) / $total );
}

And in your code you would invoke this function inside your loop which, at each iteration would produce a different value. Do not put a practical example of how it would look because I lack information that is probably before the loop posted.

    
13.05.2014 / 19:46
1

Hello, I do not know if I interpreted your question well, but from what I understood, this example below may illuminate the way.

    <?php

    $pessoas = array(
            //id da pessoa => total de atendimentos
            1=>200,
            2=>100,
            3=>400);
    //total da soma de todos os atendimentos que forma a média  = 0;            
    $total = 0;
    //pega-se o valor de cada pessoa
    foreach($pessoas as $id=>$valor){
//atribui-se um loop que faz a soma de todas as médias ao total = soma de todos atendimentos
$total += $valor;
}
    ?>
    <table collspan="5" border="1">
    <tr>
    <th>Atendimentos</th>
    <th>% Media</th>
    </tr>
    <?php
    for($i=0;$i<count($pessoas);$i++){
    ?>
    <tr>
    <td><?php echo $pessoas[$i+1]; ?></td>
     //Saída arredondamento (atendimentos da pessoa / média total ) = 0.28... * 100 = 28,... = 29 por excesso/deficiência dependendo.
     //Coloquei $i+1 para que a posição inicial do array não seja 0 e sim 1
    <td><?php echo round($pessoas[$i+1]/$total*100)."%"; ?></td>
    </tr>
    <?php
    }
    ?>
    <tr>
    <th>MEDIA GLOBAL</th>
    <th>% GERAL</th>
    </tr>
    <tr>
    <td><?php echo $total; ?></td>
    <td><?php echo round(($total/1000)*100)."%"; ?></td>
    </tr>
    </table>

I hope this helps you, either with the whole problem, or just with a part of it, good luck.

Look, for the database case I think this other example might help you get the conclusion of the first.

For the case of databases:

    <?php
    //No caso de tabelas creio que este exemplo pode ajudar a entender como chegar a conclusão do primeiro
    //Conexão PDO *-* tava com preguiça de escrever o script mysqli
    //Creio que esta parte não te interesse muito também

    try {
$conect = new PDO('mysql:host=localhost; dbname=3;','root','');
}catch(PDOException $e){
    echo "Erro ".$e->getMessage();
    }


   //Aqui o pro é a tabela que eu usei
   //$sql = requisição mysql onde seleciona a id e o preco da tabela e ordena-nos na ordem ascendente       
   $sql = $conect->query("SELECT pro.id,pro.preco FROM pro ORDER BY pro.id,pro.preco ASC");
  //Aqui a nossa variavel id será igual a uma array para poder pegar os campos da tabela em forma de array
  $id = array();
  //O mesmo acontece com a variavel preco
  $preco = array();
  //Aqui enquanto o retorno de busca de objectos na tabela for diferente de falso
  while(false !== ($row= $sql->fetch(PDO::FETCH_OBJ))){
//Array id será igual a id
$id[] .= $row->id;
//Array preco será igual a preco
$preco[] .= $row->preco;
}   

   //Aqui pode-se confirmar que na saída os valores são impressos em forma de array     
   print_r($id)."<br/>";
   print_r($preco);
   ?>

This is the first part, now, to get the output formatted or configured, simply add these lines of code right after the print_r() .

Conclusion:

    echo "<hr/>";
    $total = 0;
    foreach($preco as $ids=>$valor){
$total += $valor;
}
    //Aqui podes verificar se o valor de $total bate com os cálculos feitos ou não.
    //echo $total;
    echo "<table border='1' collspan='3'><tr><th>Vendas</th><th>% Media</th></tr>";
    for($i=0;$i<count($id);$i++){
echo "<tr><td>".$id[$i]."</td><td>".round($id[$i]/$total*100)."%"."</td></td></tr>";
}
    echo "<tr><th>Venda Geral</th><th>% Geral</th></tr>";
    echo "<tr><td>".$total."</td><td>".(($total/100)*10)."%"."</td></tr>";
    echo "</table>";
    
13.05.2014 / 22:19