2012-01-06 83 views
11

如何..just你loops..thanks幫助如何foreach循環限制在三個環路

<?php 
    foreach($section['Article'] as $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 
    endforeach; 
?> 
+0

在哪裏呢$節[ '文章']來自? – 2012-01-06 23:41:02

+1

[限制循環在php中運行的次數]的可能重複(http://stackoverflow.com/questions/1998204/limiting-number-of-times-a-loop-runs-in-php) – 2013-12-19 09:58:23

回答

23

首先,準備好你的數據

$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; 

然後顯示它

<?php foreach($section['Article'] as $article): ?> 
<tr> 
    <td><?php echo $article['title'] ?></td> 
    <td>&nbsp;<?php echo $article['link']?></td> 
</tr> 
<?php endforeach ?> 
-3

foreach循環不會是最好的,如果你需要限制它限制這種循環。嘗試使用for循環。

<?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 } ?> 

此代碼將使文本循環3次。

+1

哪種語言代碼是? – 2012-01-06 23:42:02

8

這將有助於如果你的數組數字索引

foreach($section['Article'] as $i => $article): 

    if ($i > 3) break; 

否則 - 手動增加計數器:

$i = 0; 
foreach($section['Article'] as $article): 

    if ($i++ > 3) break; 
6

它會更容易使用for()循環要做到這一點,但要回答這個問題:

<? 
$i = 0; 
foreach ($section['Article'] AS $article): 
    if ($i == 3) { break; } 
?> 
... 
<? 
$i++; 
endforeach 
?> 
66

切片數組。

foreach(array_slice($section['Article'], 0, 3) as $article): 
+9

+1這應該是正確的答案。它不會使用if語句,在一行中實現它的目標,並且顯然是foreach處理此問題的方式。那麼即使它不會得到正確的標記,這也是我將要使用的標記。我不需要10行代碼來解決一個簡單的問題。 – gcoulby 2014-03-16 05:09:10

-1

真棒一個必須嘗試這一個

<?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 
} } ?>