how to change the class of an element according to the position of the values inside a foreach?

0

I have a menu where I sort the categories. I use foreach to list and everything is working fine. My code is this:

<?php
$consulta_sub_cat = $pdo->query("SELECT * FROM ws_categoriasp");
$sub_cat = $consulta_sub_cat->fetchAll(PDO::FETCH_OBJ);
//$sub_cat = str_replace("-"," ",$lista_sub_cat);
?>

<?php
foreach ($sub_cat as $listar_cat) {
?>

    <li class="lv1"><a href="<?= BASE; ?>categorias/audio/<?= $listar_cat->sub_categoria; ?>"><?= $listar_cat->sub_categoria; ?></a></li>

<?php
}
?>

For me to change the 1 class of the 1% item from foreach I did so

<?php
$consulta_sub_cat = $pdo->query("SELECT * FROM ws_categoriasp");
$sub_cat = $consulta_sub_cat->fetchAll(PDO::FETCH_OBJ);
//$sub_cat = str_replace("-"," ",$lista_sub_cat);
?>

<?php

$list = 1;
foreach ($sub_cat as $listar_cat) {?>
<li class="lv<?= $list; ?>"><a href="<?= BASE; ?>categorias/audio/<?= $listar_cat->sub_categoria; ?>"><?= $listar_cat->sub_categoria; ?></a></li>

<?php $list = 2;
}
?>

So, when foreach lists 2, it changes the class from lv1 to lv2 , but how do I change, for example, the 4th item of foreach or 6 and so on ? That way I can only change the 1 item.

    
asked by anonymous 18.04.2017 / 23:01

2 answers

2

If you only want to define the class of the element according to the position of the values in array , you simply increment the value of $list , instead of assigning the value doir. Something like:

<?php

$list = 1;
foreach($sub_cat as $listar_cat): ?>

<li class="lv<?= $list++; ?>"><a href="<?= BASE; ?>categorias/audio/<?= $listar_cat->sub_categoria; ?>"><?= $listar_cat->sub_categoria; ?></a></li>';

<?php endforeach; ?>

If you look, the element class is class="lv<?= $list++; ?>" , where $list++ returns the current value of $list and increments it shortly after.

But the best solution, in my opinion, is to use the index of array itself:

<?php foreach($sub_cat as $i => $listar_cat): ?>

<li class="lv<?= $i; ?>"><a href="<?= BASE; ?>categorias/audio/<?= $listar_cat->sub_categoria; ?>"><?= $listar_cat->sub_categoria; ?></a></li>';

<?php endforeach; ?>

Note that in foreach there is the $i => $listar_cat statement, where $i will be the numeric index of that value in array . It will be 0 for the first value, 1 for the second, and so on. If you want the class to start at 1, just do class="lv<?= $i+1; ?>"

    
18.04.2017 / 23:12
1

Simply incrementing the variable $list before the end of the loop puts $list++;

    
18.04.2017 / 23:09