我正在爲檢查9件事情的整個腳本運行一個foreach循環。PHP foreach循環做一次而不是多次
比方說,其中五個價值「a」,其中四個價值「b」。
如何編寫只返回「a」和「b」一次的IF條件(或其他)?
我正在爲檢查9件事情的整個腳本運行一個foreach循環。PHP foreach循環做一次而不是多次
比方說,其中五個價值「a」,其中四個價值「b」。
如何編寫只返回「a」和「b」一次的IF條件(或其他)?
使用其存儲先前內容的變量,並將其與當前迭代比較(僅當類似的項目是連續工作)
$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;
}
}
// 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
$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
你能更具體的(可能會有所幫助插入代碼片段與您「內容「-objects)。
這聽起來像你正試圖獲得一個數組的獨特價值:
$values = array(1,2,2,2,2,4,6,8);
print_r(array_unique($values));
>> array(1,2,4,6,8)