簡體   English   中英

PHP foreach 循環做某事一次而不是多次

[英]PHP foreach loop to do something once instead of multiple times

我正在為整個腳本運行一個 foreach 循環來檢查 9 件事。

假設其中五個具有值“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;
  }
}

例如(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

您能否更具體一些(插入帶有“內容”對象的代碼片段可能會有所幫助)。

聽起來,您正在嘗試獲取數組的唯一值:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM