我有一个foreach循环,它根据特定条件从数组中返回数据。如何比较在循环的每次迭代中收到的数据。
我想:
我的代码看起来像的简化示例:
$count = 0;
foreach ($data[0] as $data) {
if ($data == criteria_1) {
$count +=1;
echo '$data'.$count;
break;
} elseif ($data == criteria_2) {
$count +=1;
echo '$data'.$count;
break;
} elseif ($data == criteria_3) {
$count +=1;
echo '$data'.$count;
break;
}
}
答案 0 :(得分:1)
我可能误解了你在这里要做的事情,但是这个通用模式应该可行:在循环块结束之前保存要在变量中比较的数据,然后在期间检查该变量下一次迭代。您可以使用if ($count > 0)
来避免在第一轮中执行此检查。
$count = 0;
foreach ($data[0] as $data) {
// If this is at least the second iteration of the loop,
// compare the current data to the data from the previous
// iteration.
if ($count > 0) {
if ($data === $previous) {
// Match.
// ...
} else {
// No match.
// ...
}
}
if ($data == criteria_1) {
$count +=1;
echo '$data'.$count;
break;
} elseif ($data == criteria_2) {
$count +=1;
echo '$data'.$count;
break;
} elseif ($data == criteria_3) {
$count +=1;
echo '$data'.$count;
break;
}
// Save the current data so we can access it in the next iteration.
$previous = $data;
}