Help with logic - PHP

Asked

Viewed 59 times

0

I need to make the following calculation:

(tempo protocolo1 * qtd protocolo1) + (tempo protocolo2 * qtd protocolo2)+ (tempo protocolo3 * qtd protocolo3)

So far unsuccessful. Ex:

┌──────────┬──────────┬─────┬──────────┐
│ Protocol │ Tempo    │ Qtd │ Total    │
├──────────┼──────────┼─────┼──────────┤
│ TP1      │ 00:30:00 │  2  │ 01:00:00 │
├──────────┼──────────┼─────┼──────────┤
│ TP2      │ 01:00:00 │  3  │ 03:00:00 │
├──────────┴──────────┼─────┼──────────┤
│                     │Total│ 04:00:00 │
└─────────────────────┴─────┴──────────┘

I can’t make it in four hours.

<?php

        //hora de producao total
        $acumulador="00:00:00";
        for ($i=0;$i<count($_POST['protocolos']);$i++){


        $qtd_protocolos2 = $_POST['protocolos'][$i];
        $siglas2 = $_POST['siglas'][$i]; //id_protocolo


            //pegar tempo do protocolo atraves da ID (sigla)
             $selecionar_tempo = $pdo->prepare("SELECT tempo_protocolo from protocolo where id_protocolo=:id_pro");
             $selecionar_tempo->bindParam(':id_pro',$siglas2, PDO::PARAM_INT);
             $selecionar_tempo->execute();

             $prot_tempo = $selecionar_tempo->fetch(PDO::FETCH_OBJ);
             $tempo_protocolo = $prot_tempo->tempo_protocolo;


            $tp = strtotime($tempo_protocolo);

            $tp_segundos = strtotime('1970-01-01 '.$tp.'UTC');

            $acum = strtotime($acumulador);

            $acum_segundos = strtotime('1970-01-01 '.$acum.'UTC');


            $acum_segundos =abs((pow($tp,$qtd_protocolos2))+$acum_segundos);



    }
?>
  • 1

    00:01:00 * 3 = It wouldn’t be 3 minutes? '-'

  • I typed it wrong here. Fixed. Thank you

  • You can do this in the sql query itself, which database you use?

2 answers

3


Your calculation is probably giving error because you are using the function pow (which is the high basis to the exponent). The correct is to do the same simple multiplication. $tp * $qnt_protocolos2 and so you get the desired result.

$tp = 3600; // Total de segundo desde 1970-01-01 00:00:00

echo pow( 3600, 3 ); //Saída: 46656000000 (Incorreto) | "pow" retorna (3600 * 3600 * 3600)
echo 3600 * 3;       //Saída: 10800 (Correto)

But... I leave here another way to calculate these values.


You can use the classes DateTime and DateInterval.

The class DateTime, will assist us with adding, subtracting dates etc. Already the class DateInterval, will be responsible for creating a time interval so that we can make the necessary calculations.

I’ll wear a array simple, therefore it will be necessary for you to adapt in your project.

Full and commented code:

<?php

/* Define os protocolos com os tempos o quantidade */
$protocolos = [
    'tp1' => [
        'tempo' => '00:30:00',
        'qnt'   => 2
    ],
    'tp2' => [
        'tempo' => '01:00:00',
        'qnt'   => 3
    ],
];

/* Cria uma data com o "timestamp" 0 */
$date = new DateTime("1970-01-01 00:00:00");

foreach($protocolos as $protocolo => $valor) {

    /**
     * Captura o total de segundos ocorreu  entre
     * `1970-01-01 00:00:00` e `1970-01-01 "tempo_do_protocolo"`.
     */
    $tempo = strtotime("1970-01-01 {$valor["tempo"]}") * $valor["qnt"];

    /**
     * Criamos um intervalo de segundos e somamos com a data da variável indicada
     */
    $date->add( DateInterval::createFromDateString("{$tempo} seconds") );
}

var_dump( $date->format("H:i:s") );

Demonstration in Ideone

  • 1

    I have chosen to make the answer as simple as possible, but in case you have any doubts about how it works, I can detail a few points.

  • I managed to implement! Thank you.

1

You can do the query directly in the sql query, for example in Mysql:

SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(tempo) * $qtd)) FROM protocolo

TIME_TO_SEC() - Converts time into seconds

(tempo * $qtd) - Multiply the time (in seconds) times the amount in each row

SUM() - Sum the results of all lines

SEC_TO_TIME() - Turns the seconds returned into time type (hh:mm:ss)

$qtd would be the variable that comes from the form and tempo the seat column

  • Quantity is not in table, comes from a form. Only time is.

  • I edited the answer

  • I tried it but it didn’t work.

  • Put it like you did

Browser other questions tagged

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