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 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?