PHP foreach 循环执行一次而不是多次操作


PHP foreach loop to do something once instead of multiple times

我正在为检查 9 件事的整个脚本运行一个 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;
  }
}

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