Change content on the amount of posts in a foreach loop

时间:2016-04-15 11:11:54

标签: php foreach

Hello I want to change the content on the amount of posts so if the foreach loop got only 2 posts it should say 2. But it is not working?

<?php if (!empty($iconMenu)) { ?>
<nav class="menu-top">
<?php $i = 0; 
foreach($iconMenu as $icon) {
    $page = Website::getActiveTreeBranch($icon['link']);
    if ($page !== false) {
        $i++;

        if($i=1){ ?>
        1 
        <?php  } ?>

        <?php if($i=2){ ?>
        2 
        <?php  } ?>   

    <?php  }} ?>
<?php } ?>
</nav>

3 个答案:

答案 0 :(得分:0)

Simple Typo:

= is assignment operator and == is equality check operator.

Change code:

if($i=1){ ?>
1 
<?php  } ?>
<?php if($i=2){ ?>

To

if ($i == 1) {
 echo '1' 
}
if($i == 2) {

So, the final (cleaned up code):

<?php
if (! empty($iconMenu)) {
    echo '<nav class="menu-top">';
    $i = 0;
    foreach ($iconMenu as $icon) {
        $page = Website::getActiveTreeBranch($icon['link']);
        if ($page !== false) {
            $i++;
            if ($i == 1) {
                echo '1';
            }
            if ($i == 2) {
                echo '2 ';
            }
        }
    }
}
echo '</nav>';
?>

答案 1 :(得分:0)

这个答案不是针对这个问题,而是为了帮助他如何使用php标签。

<?php $i = 0; 
foreach($iconMenu as $icon) {
$page = Website::getActiveTreeBranch($icon['link']);
if ($page !== false) {
    $i++;

    if($i==1){
      Echo "1"; 
    }

    if($i==2){ 
      echo "2"; 
    }   

  }}
 } ?>
</nav>

我没有仔细检查我在手机上输入的{和}是否正确。

编辑:如果=

,我忘记编辑错误的内容

答案 2 :(得分:0)

我修好了,我不得不改用Count