我正在为整个脚本运行一个foreach循环来检查9件事。
假设其中五个具有值“a”,其中四个具有值“b”。
如何编写仅返回“a”和“b”一次的IF条件(或其他内容)?
答案 0 :(得分:2)
使用存储先前内容的变量,并将其与当前迭代进行比较(仅当相似项目是连续的时才有效)
$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
答案 1 :(得分:1)
你能否更具体一点(在你的“内容” - 对象中插入代码片段可能会有所帮助。)
听起来,您正在尝试获取数组的唯一值:
$values = array(1,2,2,2,2,4,6,8);
print_r(array_unique($values));
>> array(1,2,4,6,8)