简体   繁体   English

如何在foreach循环codeigniter中跳过/减去第一个值

[英]How to skip/subtract first value in foreach loop codeigniter

This is in my view: 我认为这是:

<?php foreach ($serial_items as $k => $v): ?>
    <?php foreach ($v['children'] as $a => $b): ?>
    <li>
        <span class="info-bold" style="font-size:12px;"><?=$b->serial_num?></span>
    </li>
    <?php endforeach; ?> 
<?php endforeach; ?>

Q: how can skip first value in $v ? 问:如何跳过$v第一个值? or I want to start the loop from 2nd up to last item of $v . 或者我想从$v第二项到最后一项开始循环。

Not sure if it will be a good solution or not, but it will work for you. 不知道这是否将是一个好的解决方案,但是它将为您工作。

<?php foreach ($serial_items as $k => $v): ?>
         <?php $counter =0;  foreach ($v['children'] as $a => $b): ?>
              <?php if($counter == 0) continue; //if counter is 0, it means you are at first value of $v array, so skip it and continue the loop ?>
              <li>
                 <span class="info-bold" style="font-size:12px;"><?=$b->serial_num?></span>
              </li>
         <?php $counter++; ?>
         <?php endforeach; ?> 

As you can see i have created a counter variable $counter in the top foreach loop, where its value is 0. Now in the second loop, i check if $counter is equal to 0, if zero, it means i am at first element of $v array, so it skips it and continue to the inner loop by using continue . 如您所见,我在顶部的foreach循环中创建了一个计数器变量$ counter,其值是0。现在在第二个循环中,我检查$ counter是否等于0,如果为零,则意味着我在第一个元素上$ v数组,因此它会跳过它,并通过使用continue继续进入内部循环。 $counter is incremented with each iteration of inner foreach loop and is set to zero again with each iteration of outer foreach loop. $ counter在内部foreach循环的每次迭代中增加,并在外部foreach循环的每次迭代中再次设置为零。

I hope this will help. 我希望这将有所帮助。

Note: This code i not tested, it is just to give you an idea. 注意:此代码未经测试,仅供参考。 It may or may not work. 它可能会或可能不会。 Kindly adjust it according to your needs if you are using it 如果您正在使用,请根据需要进行调整

<?php foreach ($serial_items as $k => $v): ?>
<?php $i=0;?>
<?php foreach ($v['children'] as $a => $b): ?>
 <?php if($i>0){?>
<li>
    <span class="info-bold" style="font-size:12px;"><?=$b->serial_num?></span>
</li>
<?php $++;}?>
<?php endforeach; ?> 
<?php endforeach; ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM