2011-10-07 24 views
4

該代碼循環一個數組並顯示用戶的所有視圖。現在事情改變了,我只需要顯示一個foreach循環的結果。我怎麼做?如何從foreach中獲取一個結果(PHP)

<table class="report_edits_table"> 
<thead> 
    <tr class="dates_row"> 
    <?php foreach($report['edits'] as $report_edit) : ?> 
    <td colspan="2" report_edit_id="<?php echo $report_edit['id'] ?>"><div class="date_container"> 
    <?php if($sf_user->hasCredential(Attribute::COACHING_EDIT_ACCESS)) : ?> 
     <span class="ui-icon ui-icon-trash">Remove</span> 
    <?php endif?> 
    <?php echo "View " . link_to($report_edit['created'], sprintf('coaching/viewReportEdit?reportedit=%s', $report_edit['id']), array('title' => 'View This Contact')) ?> </div></td> 
    <?php endforeach ?> 
    </tr> 
</thead> 
<tbody> 
    <?php foreach($report['edits_titles'] as $index => $title) : ?> 
    <tr class="coach_row"> 
    <?php for ($i=max(0, count($report['edits'])-2); $i<count($report['edits']); $i++) : $report_edit = $report['edits'][$i] ?> 
    <td class="name_column"><?php echo $title ?></td> 
    <td class="value_column"><?php echo $report_edit[$index] ?></td> 
    <?php endfor ?> 
    </tr> 
    <?php endforeach ?> 
</tbody> 

+0

我真的不知道你想做什麼,但你總是可以'打破;'跳出'的foreach( )' – jprofitt

回答

2

簡單轉換使用break命令:

<?php for ... ?> 
    ... stuff here ... 
    <?php break; ?> 
<?php endfor ... ?> 

一個更好的解決辦法是徹底清除foreach

1

最簡單的方法?

break作爲您的foreach的最後一行。它會執行一次,然後退出。 (只要其中元素你停下來是沒有意義的)。

次要方法:你$report['edits']$report['edits_titles']獲得元素上,失去了for循環,並引用元素上使用array_poparray_shift你只是檢索。

例如:

// 
// current 
// 
foreach ($report['edits'] as $report_edit) : 
    /* markup */ 
endforeach; 

// 
// modified version 
// 
$report_edit = array_shift($report['edits']); 
    /* markup */ 
3

方式大量

  1. 訪問所討論的陣列元件直接
  2. 更新任何邏輯取/的索引生成所述陣列,以僅返回的元件興趣
  3. 使用for循環在單個循環後終止
  4. arr ay_filter您的陣列來獲取感興趣的元素
  5. 歇在您的foreach循環的末尾,以便它在第一次迭代之後終止
  6. 有條件的檢查在foreach循環中,只有輸出標記指數,如果指數感興趣的元素相匹配
  7. 等等

我建議剛開始的利息(名單上的數字2),因爲它意味着更少的數據在你的代碼彈跳數組元素(也可能是你的PHP箱和數據庫之間是否你正在從SQL服務器填充數組)

1

使用<?php break ?><?php endforeach ?>

4

這聽起來像你想抓住從一個數組的第一個元素,而無需通過他們的休息有循環。

PHP爲這種情況提供了一組函數。

要獲得數組中的第一個元素,請使用reset()函數將數組指針定位到數組的起始位置,然後使用current()函數讀取指針正在查看的元素。

所以,你的代碼應該是這樣的:

<?php 
reset($report['edits']); 
$report_edit = current($report['edits']); 
?> 

現在你可以用$report_edits工作,而無需使用foreach()循環。

(注意,數組指針不實際默認的第一個記錄開始,所以你可以跳過reset()電話,但最好的做法不是這樣做,因爲它可能已在其他地方在你的代碼改變,而你意識到這一點)

如果你想在此之後移動到下一個記錄,你可以使用next()函數。正如你所看到的,如果你願意,理論上可以使用這些函數來編寫另一種類型的foreach()循環。以這種方式使用它們沒有任何意義,但它是可能的。但是它們確實允許對數組進行更細粒度的控制,這對於像您這樣的情況非常方便。

希望有所幫助。

1
example :: 

<?php 
    foreach ($this->oFuelData AS $aFuelData) { 
    echo $aFuelData['vehicle']; 
    break;      
    } 
?> 
0

你也可以用它來參考

foreach($array as $element) { 
    if ($element === reset($array)) 
     echo $element; 

    if ($element === end($array)) 
     echo $element; 
    } 
相關問題