List data in separate columns

1

I have the following list coming from the database

<ul class="list-marked">
    <?php foreach($cidades_presentes as $valor){ ?>
    <li><a href="#"><?php echo $valor->categoria; ?></a></li>
    <?php } ?>                  
</ul>   

$cidades_presentes returns 15 cities in the following format:

Array
(
    [0] => stdClass Object
        (
            [id] => 1
            [id_cidadesbairros] => 0
            [categoria] => Foz do Iguaçu
            [ativo] => 1
        )

    [1] => stdClass Object
        (
            [id] => 4
            [id_cidadesbairros] => 0
            [categoria] => São Miguel do Iguaçu
            [ativo] => 1
        )

    [2] => stdClass Object
        (
            [id] => 6
            [id_cidadesbairros] => 0
            [categoria] => Medianeira
            [ativo] => 1
        )

)

My question is: If I return 15 lines, I need to display it as follows:

<div class="col-md-6">
8 itens da lista aqui
</div>

<div class="col-md-6">
7 itens da lista aqui
</div>

How can I do this?

Update, Function that searches cities:

public function get_cidades_presentes(){
    $this->db->where("id_cidadesbairros", '0');
    return $this->db->get('cidadesbairros')->result();
}
    
asked by anonymous 14.12.2016 / 22:39

1 answer

2

A simple way to split a array into equal blocks (where possible) is by using the function array_chunk

  

link

To split your list of cities into two columns, and then display this would be a very simple alternative:

$colunas = 2;
$linhas  = round(count($cidades) / $colunas, 0, PHP_ROUND_HALF_UP);
$blocos  = array_chunk($cidades, $linhas);

To display the question one block at a time:

for( $i = 0; $i < $colunas; ++$i ) {
   echo '<div class="col-md-3">';
   foreach( $blocos[$i] as $bloco ) {
      echo '<tagDesejada>'.$bloco['categoria'].'</tagDesejada>';
   }
   echo '</div>';
}

See working at IDEONE .

(in the case of objects, as you already noticed, would be $bloco->categoria )


If it were to display side by side in a table:

for( $i = 0; $i < $linhas; ++$i ) {
    echo '<tr>';
    echo '<td>'.$blocos[0][$i]['categoria'].'</td>';
    echo '<td>'.$blocos[1][$i]['categoria'].'</td>';
    echo '</tr>';
}

See working at IDEONE .

(in the latter case, it would be nice to have if in the last column to identify the end of the block, since it will not always have all rows)

    
14.12.2016 / 23:47