duanqi6007
2016-01-14 11:48
浏览 359
已采纳

获取foreach循环后的最后一个数组索引

Hi I'm trying to find the last array of $linkNumber from my for each loop as i have an image outside the foreach loop that needs the data-slide-index to be the last array plus 1. Any help how to achieve this?

<?php $linkNumber = 0;?>  

<?php foreach ($variables as $variable){ ?>
     <img src="$variable" data-slide-index="$linkNumber++"/>
<?php } ?>
<img src="#" data-slide-index="<?php $linkNumber + 1;?>"

图片转代码服务由CSDN问答提供 功能建议

我正在尝试从我的每个循环中找到$ linkNumber的最后一个数组,因为我在外面有一个图像 需要data-slide-index的foreach循环是最后一个数组加1.任何帮助如何实现这一点?

 &lt;?php $ linkNumber = 0;?&gt;  
 
&lt;?php foreach($ variables as $ variable){?&gt; 
&lt; img src =“$ variable”data-slide-index =“$ linkNumber ++”/&gt; 
&lt;?php}?  &gt; 
&lt; img src =“#”data-slide-index =“&lt;?php $ linkNumber + 1;?&gt;”
   
 
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • donglanfu5831 2016-01-14 11:59
    已采纳

    If we ignore that your variables won't be printed or evaluated at all for the moment; essentially what you are doing is correct. Your problem is most of your logic isn't being executed.

    You need to explicitly echo variables and evaluations should be inside a PHP block, as follows

    <?php
    $linkNumber = 0;
    
    foreach ($variables as $variable) :
        ?>
        <img src="<?= $variable; ?>" data-slide-index="<?= $linkNumber; ?>"/>
        <?php
        $linkNumber++;
    endforeach;
    ?>
    
    <img src="#" data-slide-index="<?= $linkNumber; ?>"
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • duannai5879 2016-01-14 12:04

    This should work:

    <?php $linkNumber = 0;?>  
    
    <?php foreach ($variables as $variable){ ?>
     <img src="$variable" data-slide-index="$linkNumber++"/>
     <?php } ?>
     <img src="#" data-slide-index="<?php echo count($variables) + 1;?>"
    
    评论
    解决 无用
    打赏 举报
  • dongli7236 2016-01-14 12:05

    Your code seems to work except for some syntax issues. Eliminating these this code works for me:

    <?php
    $linkNumber = 0;
    
    $variables = array("test", "test2");
    
    foreach ($variables as $variable){
         echo '<img src="' . $variable . '" data-slide-index="' . $linkNumber++ . '"/>' . "
    ";
    }
    echo '<img src="#" data-slide-index="' . $linkNumber . '">';
    
    ?>
    

    http://ideone.com/01cWNg

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题