[英]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;
}
}
// 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.