Calculate total "cell" average in php

Asked

Viewed 2,263 times

1

I need to make a calculation as a result that I get from the query where he made only a division of the total value of a person by the average that was obtained from all. See the image:

inserir a descrição da imagem aqui

I don’t know if it’ll help, but part of the code is like this:

$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 style of code isn’t right, but I’m still learning. In case you need any more information I’m available to help to be helped.

  • Yes, I’ve tried to do something here, but nothing that would work. =(

  • To achieve something like this, $resultsPorc = round(($results['total'] * 100) / 354); but I need that instead of 354 (which was a test) the dynamic result of the average of all appointments.

  • Do as in the shopping carts, create a variable $media = 0 out of the loop and within the loop sum it $media += $soma_total and then print the $media out of the loop again.

  • I think I understand your idea, but not how to apply it to my case.

  • Give me a few minutes I’m on tel. when I get back to PC I have to show you the practical way.

2 answers

3

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

For table Heading of your image you want to show the percentage of attendance of each person (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

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

D = BC / A

Being:

  • To the Total of Calls
  • B the total percentage (always 100)
  • C the number of calls made by the person concerned
  • D the value of the equation you need to discover

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, in that cell of the table;

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

And in your code you would invoke this function within your loop which, with each iteration, would produce a different value. Not put a practical example of how it would look because I lack information that are probably before the loop posted.

  • Bruno, thanks for the comment I will see here what I can do but above what I posted code I have only the bank selects and something else that (edited) there.

1

Hello, I do not know if I understood your doubt well, but from what I understood this example below maybe of 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 a piece of it, good luck.

Look, for the database case I think this other example might help you come to 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, just add these lines of code right after the print_r().

Completion:

    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>";
  • I just don’t understand how I’m going to do this array to assign id => value in my case.

  • Let’s say the variable $people equals your variable $results.

  • @phpricardo Look, I added a part to my answer, maybe this helps you, in case the id is an array and you can take each position of the array following the same steps of the first example and then do the same with the value (in my case price) and make the link id=>valor(preco)

Browser other questions tagged

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