简体   繁体   English

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

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

I'm running a foreach loop for the whole script that checks 9 things.我正在为整个脚本运行一个 foreach 循环来检查 9 件事。

Let's say five of them have value "a" and four of them have value "b".假设其中五个具有值“a”,其中四个具有值“b”。

How do I write an IF condition (or something) that only returns "a" and "b" once?如何编写仅返回“a”和“b”一次的 IF 条件(或其他条件)?

Simple method (check last value)简单方法(检查最后一个值)

Use a variable which stores the previous contents, and compare it with the current iteration (only works if the similar items are sequential)使用存储先前内容的变量,并将其与当前迭代进行比较(仅当相似项目是连续的时才有效)

$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;
}

More robust method (store used values on an array)更健壮的方法(将使用的值存储在数组中)

Or, if you have complex objects, where you need to check an inner property and the like things are not sequential, store the ones used onto an array:或者,如果你有复杂的对象,你需要检查一个内部属性,并且类似的东西不是顺序的,将使用的那些存储到一个数组中:

$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;
  }
}

For example (1):例如(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

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

Could you be more concrete (it might be helpful to insert a code-snippet with your "content"-objects).您能否更具体一些(插入带有“内容”对象的代码片段可能会有所帮助)。

It sounds like, you are trying to get unique values of an array:听起来,您正在尝试获取数组的唯一值:

$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