Division of records listed in PHP Batch

1

I have a listing with 37 items, returning in array form from the database as follows:

SELECT * FROM tabela WHERE id = '5';

In this listing, I have a dividend:

$total = 37; // quantidade retornada do banco de dados
$dividir = 2; // quantidade que eu desejo dividir 
$resultado = floor($total/$dividir); // arredondo para baixo

The total of the result will be 18. There is 1 item remaining.

What I need is to insert this data into the database as follows:

INSERT INTO tabela2 (total, lote, campo1, campo2) 

What it represents: total = 37, lot = 1 (I divided by 2, then the first 18 records will be with lot 1) and the other fields

INSERT INTO tabela2 (total, lote, campo1, campo2) 

What it represents: total = 37, lot = 2 (I divided by 2, then the other 18 records will be with lot 2) and the other fields

And finally, since there is one left, I need to insert it as a third batch

INSERT INTO tabela2 (total, lote, campo1, campo2) 

What it represents: total = 37, lot = 3 (I divided by 2, then what's left is lot 3) and the other fields

How would I do so that I can correctly insert into the database? My question is simply the division of records in batches.

    
asked by anonymous 27.10.2016 / 14:56

1 answer

2

I've modified the code, see if it caters better:

<?php
$registros = [];
for($j = 0; $j < 51; $j++){
    $registros[$j] = "Registro " . $j;
}   

$total = count($registros);
$dividir = 10;
$resultado = floor($total/$dividir);
$totalLotes = $dividir + ($total % $dividir > 0 ? 1 : 0);

echo "Total por lote: $resultado. <br />";
echo "Total de lotes:  {$totalLotes}.<br />";

$lote = 1;
$contador = 0;
foreach($registros as $chave => $registro){
    if($contador == $resultado){
        $contador = 0;
        $lote++;
    }
    $contador++;

    echo "INSERT INTO tabela2 ({$total}, {$lote}, {$registro}, {$chave})" . "<br />";

}

?>
    
27.10.2016 / 17:23