2012-04-07 65 views

回答

2

簡單的方法(檢查最後一個值)

使用其存儲先前內容的變量,並將其與當前迭代比較(僅當類似的項目是連續工作)

$last_thing = NULL; 
foreach ($things as $thing) { 
    // Only do it if the current thing is not the same as the last thing... 
    if ($thing != $last_thing) { 
    // do the thing 
    } 
    // Store the current thing for the next loop 
    $last_thing = $thing; 
} 

更強大方法(將已使用的值存儲在數組上)

或者,如果您有複雜的對象,需要檢查內部屬性等等,則事件不是順序的,請將使用的對象存儲到數組中:

$used = array(); 
foreach ($things as $thing) { 
    // Check if it has already been used (exists in the $used array) 
    if (!in_array($thing, $used)) { 
    // do the thing 
    // and add it to the $used array 
    $used[] = $thing; 
    } 
} 

例如(1):

// Like objects are non-sequential 
$things = array('a','a','a','b','b'); 

$last_thing = NULL; 
foreach ($things as $thing) { 
    if ($thing != $last_thing) { 
    echo $thing . "\n"; 
    } 
    $last_thing = $thing; 
} 

// Outputs 
a 
b 

例如(2)

$things = array('a','b','b','b','a'); 
$used = array(); 
foreach ($things as $thing) { 
    if (!in_array($thing, $used)) { 
    echo $thing . "\n"; 
    $used[] = $thing; 
    } 
} 

// Outputs 
a 
b 
1

你能更具體的(可能會有所幫助插入代碼片段與您「內容「-objects)。

這聽起來像你正試圖獲得一個數組的獨特價值:

$values = array(1,2,2,2,2,4,6,8); 
print_r(array_unique($values)); 
>> array(1,2,4,6,8)