how to limit foreach loop to three loops

后端 未结 6 2326
梦如初夏
梦如初夏 2020-12-13 10:31

how to limit this loop ..just thee loops..thanks for helping



    
               


        
相关标签:
6条回答
  • 2020-12-13 11:14

    first, prepare your data

    $i = 1;
    $data = array();
    foreach($section['Article'] as $article ) {
      if($article['status']== 1) {
        $article['link'] = $html->link('View', '/articles/view/'.$article['id']);
        $data[] = $article;
        if ($i++ == 3) break;
      }
    }
    $section['Article'] = $data;
    

    then display it

    <?php foreach($section['Article'] as $article ): ?>
    <tr>
      <td><?php echo $article['title'] ?></td>
      <td>&nbsp;<?php echo $article['link']?></td>
    </tr>
    <?php endforeach ?>
    
    0 讨论(0)
  • 2020-12-13 11:14

    It'd be easier to use a for() loop to do this, but to answer the question:

    <?
    $i = 0;
    foreach ($section['Article'] AS $article):
        if ($i == 3) { break; }
    ?>
    ...
    <?
    $i++;
    endforeach
    ?>
    
    0 讨论(0)
  • 2020-12-13 11:23

    A foreach loop wouldn't be the best if you need to limit it. Try using a for loop.

    <?php
    
    for(i=1; i<=3; i++)
    {  
        $article = $section['Article'];
    
    
                         ?>
                        <tr>
                            <td><?php if($article['status']== 1){echo $article['title'];}  ?></td>
                            <td><?php  if($article['status']== 1){echo '&nbsp;'.$html->link('View', '/articles/view/'.$article['id']);}?></td>
                        </tr>
                        <?php } ?>
    

    This code will make the text loop 3 times.

    0 讨论(0)
  • 2020-12-13 11:30

    This will help if your array is numerically indexed

    foreach($section['Article'] as $i => $article ):
    
        if ($i > 3) break;
    

    Otherwise - manually increment the counter:

    $i = 0;
    foreach($section['Article'] as $article ):
    
        if ($i++ > 3) break;
    
    0 讨论(0)
  • 2020-12-13 11:31

    Awesome one must try this one

    <?php $count = 0; $pages = get_pages('child_of=1119&sort_column=post_date&sort_order=desc');   foreach($pages as $page) {
    $count++;
    if ( $count < 50) {  // only process 10 ?>
     <div class="main_post_listing">  <a href="<?php echo get_page_link($page->ID) ?>"><?php echo $page->post_title ?></a><br /></div>
    <?php
    }  } ?> 
    
    0 讨论(0)
  • 2020-12-13 11:32

    Slice the array.

    foreach(array_slice($section['Article'], 0, 3) as $article ):
    
    0 讨论(0)
提交回复
热议问题