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 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起