我正在为检查 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;
}
}
// 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
您能否更具体一些(插入带有“内容”对象的代码片段可能会有所帮助)。
听起来,您正在尝试获取数组的唯一值:
$values = array(1,2,2,2,2,4,6,8);
print_r(array_unique($values));
>> array(1,2,4,6,8)