简体   繁体   English

Foreach循环,偏移或跳过循环中的第一篇文章

[英]Foreach loop, offset or skip first post in the loop

I'm trying to figure this out for hours but I can't. 我想弄清楚几个小时,但我做不到。 I just want to show the second post and skip the first one, just like the Wordpress offset function. 我只想显示第二个帖子,而跳过第一个,就像Wordpress偏移功能一样。 I'm using AW blog extension for Magento and I want to skip the first post in the recent blog posts. 我正在使用Magento的AW博客扩展程序,并且想跳过最近博客文章中的第一篇文章。 Below is my modified code showing one post recent post in a homepage block. 以下是我修改的代码,显示了主页块中的一篇最新帖子。 I just want to create another block that will show the second recent post. 我只想创建另一个显示第二篇文章的块。 :( :(

<?php $posts = $this->getPosts(); ?>
<div id="messages_product_view">
    <?php Mage::app()->getLayout()->getMessagesBlock()->    setMessages(Mage::getSingleton('customer/session')->getMessages(true)); ?>
    <?php echo Mage::app()->getLayout()->getMessagesBlock()->getGroupedHtml(); ?>
</div>

<?php 
 foreach ($posts as $post):
 if ($i++ >= 1) break;
?>


    <div class="postWrapper">
        <div class="postTitle">
            <h3><a href="<?php echo $post->getAddress(); ?>" ><?php echo $post->getTitle(); ?></a></h3>
        </div>
        <div class="postContent"><?php echo $post->getPostContent(); ?></div>
    </div>
<?php endforeach; ?>

I will recommend you to check the count and after printing it stop the loop, otherwise it will loop the entire array to the end and print just the second iteration. 我建议您检查计数,并在打印后停止循环,否则它将整个数组循环到最后并仅打印第二次迭代。

$i=0;    
foreach ($posts as $post){
    if ($i==1) {
       //print your div here
       $i++; //added here after edit.
       continue;
    }else if ( $i>1 ){
        break;
    }
    $i++;
}

This way it will only iterate twice. 这样,它只会迭代两次。

Try changing: 尝试更改:

foreach ($posts as $post):
if ($i++ >= 1) break;

to: 至:

//set $i outside of loop
$i=0;    
foreach ($posts as $post):
if ($i==0) {
  $i++;
  //skip the first record
  continue;
}

Try this - 尝试这个 -

<?php $i=1;
 foreach ($posts as $post):
 if ($i > 1) {
?>
    <div class="postWrapper">
        <div class="postTitle">
            <h3><a href="<?php echo $post->getAddress(); ?>" ><?php echo $post->getTitle(); ?></a></h3>
        </div>
        <div class="postContent"><?php echo $post->getPostContent(); ?></div>
    </div>
<?php }
$i++;
endforeach; ?>

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

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