List data in separate columns

Asked

Viewed 512 times

1

I have the following list 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 you 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?

Updating, Function that searches the cities:

public function get_cidades_presentes(){
    $this->db->where("id_cidadesbairros", '0');
    return $this->db->get('cidadesbairros')->result();
}

1 answer

2


A simple way to divide one array in equal blocks (within the possible) is using the function array_chunk

http://php.net/manual/en/function.array-chunk.php

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 according to 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 on IDEONE.

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


If you were to display side by side on 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 on IDEONE.

(in the latter case, a if in the last column to identify the end of the block, since it will not always have all lines)

Browser other questions tagged

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