How to insert a header to each N records?

5

How can I insert a header to each N records? Like ...

<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 listing of records.

    
asked by anonymous 06.10.2014 / 05:51

2 answers

11

You need the Module operator ( % ) , which is the rest of the division of $a by $b . Before the loop we open a counter with 0 and we increase $count++ . And when ( $count % 4 ) === 0 we 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

    
06.10.2014 / 06:39
3

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

It will segment its array to each N element 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";
        }
    }
    
06.10.2014 / 14:12