Divide the results of mysql into blocks

1

I have a system from which to register the number of people in a certain establishment that goes from 1 to 200 and each establishment holds up to 3 people. How would I do that by bringing mysql this amount, be divided into blocks. For example:

How I'm currently bringing

<?php
....
$c = 1;
while($jm = mysqli_fetch_object($sqlMostrar)){
   $mostrar .= "Estabelecimento " . $c . "<br>";
   $mostrar .= $jm->Nome. " " .$jm->Idade;
 $c++; 
}

This way it brings racing and not in blocks. I would like you to bring this result as follows. Let's assume that the client has registered 09 people:

**Estabelecimento 1**
Fernando Pessoa 32 anos
Ruth Cardoso 56 anos
Santos Dumont 60 anos

**Estabelecimento 2**
Carlos Drummond de Andrade 70 anos
Mario Lago 72 anos
Manuel Bandeira 60 anos

**Estabelecimento 3**
Olavo Bilac 22 anos
Cecília Meireles 25 anos
Gonçalves Dias 55 anos
    
asked by anonymous 30.09.2015 / 17:35

2 answers

2

I do not know if for your case this would be advantageous because of perfomance, but what could be done is to split the result through the array_chunk function. For this we would have to use Mysqli::fetch_all , instead of fetch .

$chunks = array_chunk(mysqli_fetch_all($sql), 3)

And then:

<?php foreach ($chunks as $key => $results) : ?>
   Estabelecimento <?= $key+1?>
   <?php foreach ($results as $row) : ?>
      ...
   <?php endforeach ?>
<?php endforeach ?>

Another solution is to check in a loop if the number is divisible by three, so you can generate this "3-by-3 jump."

Example:

$c = 1;
$d = 0;
while($jm = mysqli_fetch_object($sqlMostrar)){

   if ($d++ % 3 == 0) {
      $mostrar .= "Estabelecimento " . $c . "<br>";
      $c++;
   }

   $mostrar .= $jm->Nome. " " .$jm->Idade;
}
    
30.09.2015 / 17:45
1

I did not understand well, but I will assume that the people register is sequential, and you are simply distributing the people. Also it has not been defined that the break is vertical or horizontal.

# SIMULA AS PESSOA
$pessoa = array();
for ($i=0; $i < 9; $i++){ 
    $pessoa[] = array(
        'nome' => "Pessoa {$i}",
    );
}

# CRIA ARRAY HIPOTIPÓTICO
$estabelecimento = array();
$estabelecimento2 = array();
$x = 0;
foreach ($pessoa as $k => $options){
    # QUEBRA HORIZONTAL
    $estabelecimento[$k%3][] = $options;

    # QUEBRA VERTIVAL
    if($k%3 == 0){
        $estabelecimento2[++$x][] = $options;
    }else{
        $estabelecimento2[$x][] = $options;
    }
}

echo '<pre>';
print_r($estabelecimento);
print_r($estabelecimento2);
    
30.09.2015 / 18:52