douzhun4124 2016-02-26 19:47
浏览 37
已采纳

Echo基于PHP foreach循环中的实例数

I have the following foreach loop:

<?php if(!empty($strategy->assisting)):?>
     <ul class="needs-padding">
      <?php foreach($strategy->assisting as $asst): ?>
          <li><?= $asst->full_name; ?></li>
      <?php endforeach; ?>
      </ul>
 <?php endif; ?>

Rather than just spitting out all the $asst inside of li's, I need to echo 'multiple' if there is more than one (with the list after appearing after so show I can hide/show it with js) or echo out just the $asst if there is only one instance.

I tried this but its obviously wrong as it just prints out 'multiple' for every instance of $asst.

                  <?php if(!empty($strategy->assisting)):?>
                        <ul class="needs-padding assisting-members">
                            <?php $count = 0; ?>
                            <?php foreach($strategy->assisting as $asst): ?>
                                <?php $count ++; ?>
                                <?php if($count > 1){
                                    echo '<a href="#">Multiple</a>';
                                    // echo '<li>' . $asst->full_name . '</li>';
                                } else {
                                    echo '<li>' . $asst->full_name . '</li>';
                                } ?>
                            <?php endforeach; ?>
                        </ul>
                    <?php endif; ?>
  • 写回答

2条回答 默认 最新

  • duanjihe5180 2016-02-26 20:11
    关注

    Change your code as shown below:

    <?php if(!empty($strategy->assisting)):?>
         <?php $count = count($strategy->assisting); ?>
         <ul class="needs-padding">
          <?php foreach($strategy->assisting as $k => $asst): ?>
              <?php if ($count > 1 && $k == 0) echo '<a href="#">Multiple</a>'; ?>
              <li <?php if ($count > 1) echo "style='display:none;'"; ?>><?= $asst->full_name; ?></li>
          <?php endforeach; ?>
          </ul>
     <?php endif; ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥66 如何制作支付宝扫码跳转到发红包界面
  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题