Division of listed records into PHP Batches

Asked

Viewed 75 times

1

I have a list of 37 items, returning in the form of a database array 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 result will be 18. Then 1 item remains.

What I need is to insert this data into the database in the following way:

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, as one remains, I need to insert as a third batch

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

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

How would I get it into the database correctly? My question boils down to just splitting the records into batches.

1 answer

2


I modified the code, see if it fits 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 />";

}

?>
  • It’s almost that, but it does not return what it would take, the lots do not match, I need to insert each one in your lot... but it’s around, I was told that I can use as a pagination effect, and insert according to the pages, using the for, but I could not do.

  • @Andrébaill, I modified the code. Take a look.

Browser other questions tagged

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