How to insert a header to each N records?

Asked

Viewed 183 times

5

How can I enter a header for each N records? Type ...

<h1>CABECALHO</h1>
     Cadastro 1
     Cadastro 2
     Cadastro 3
     Cadastro N
<h1>CABECALHO</h1>
     Cadastro ..
     Cadastro ..
     Cadastro ..
     Cadastro N
<h1>CABECALHO</h1>
     Cadastro ..
     Cadastro ..
     Cadastro ..
     Cadastro N
<h1>CABECALHO</h1>
     Cadastro ..
     Cadastro ..
     Cadastro ..
     Cadastro N

Mysql does this in the list of records.

  • 3

    make a $i=0 loop $i++ and when $i===4 you print the header.

  • What is different from this one? http://answall.com/questions/15869/executar-script-a-cada-1000-registros-consulted

  • 1

    @Bigown In both the answer is the module operator, but this goes straight to the point. I think I can live with both, but if I were to close I would close the other as a duplicate of this.

2 answers

11

You need the module operator (%), which is the rest of the $a for $b. Before the loop we open a counter with 0 and increase $count++.
And when ( $count % 4 ) === 0 print the header.

$count = 0;
foreach( $array_var as $item ){
    if( ( $count % 4) === 0 )
        echo '<h1>CABECALHO</h1>'; // aspas simples quando não tem PHP dentro
    echo "$item<br />";           // duplas quando queremos imprimir variáveis dentro da string
    $count++;
}

Ideone

3

Another way to do this without using a counting array is through array_chunk.

It will segment your array to each N elements generating a second array. Just insert the header between them:

<?php

    $cadastros = ['item1', '...', 'itemN'];

    $numeroSegmentos = 5;

    foreach (array_chunk($cadastros, $numeroSegmentos) as $chunks) {
        echo "Cabeçalho\n";

        foreach ($chunks as $cadastro) {
            echo "\t$cadastro\n";
        }
    }

Browser other questions tagged

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