2011-02-01 33 views
-2

我很困難,如果你有2分鐘請別人幫忙。從循環中獲取下一個陣列

我有一個foreach在那裏我得到的值從會話類似

foreach ($result as $i => $item) { 

     $values_array = explode("\n",$get_widths); // outputs Array ([0] => 120 [1] => 180) 
     // here I need to echo the value from the array but only ONCE 
} 

的問題是,這是使用2個或更多的項目和陣列輸出被重複每一次,所以如果2項我得到 陣列([0] => 120 [1] => 180)陣列([0] => 120 [1] => 180)或代替

對於實際的代碼見這裏

<?php 
foreach ($list as $i => &$item){ 
    $i=0; 
    $is_group     = $item_params->get('is_group');  
    $group_widths    = $item_params->get('group_widths');  
    $group_widths_array   = explode("\n",$group_widths); 

    if($is_group == 1){ 

     echo $group_widths_array[$i]; 
    } 



} 
?> 

請注意我不能移到foreach之外。謝謝

+0

我想你會需要擺脫foreach,並使用`for` – 2011-02-01 20:43:32

+0

我不能這樣做,必須使用foreach – Benn 2011-02-01 20:47:11

+0

爲什麼?這是作業,還是紀律測試? – Andrew 2011-02-01 20:49:03

回答

0

我完全缺少這個環的點...

您遍歷數組,分配關鍵$i和值$item但你設置$i爲0,呼應$group_widths_array[0]每當你的條件得到滿足,$item你根本不用...

這不可能是正確的,可以嗎?

無論如何,在我看來,你的輸出重複的原因是你每次輸出$group_widths_array[0],並且$is_group在每次迭代中都是相同的。

1

我只是簡單地使用某種標誌變量來確定我們是否已經處理過。

$values_array = explode("\n",$get_widths); 
if (!isset($we_have_outputted)) { 
    echo '<pre>'. print_r($values_array, true) .'</pre>'; 
    $we_have_outputted = true; 
}