假设我有一个包含日期和季节的数组,每天有一个条目。我想仅在季节值发生变化时打印数组行。
数组看起来像那样:
2009-10-28 00:00:00 (good season)
2009-10-29 00:00:00 (good season)
2009-10-30 00:00:00 (good season)
2009-10-31 00:00:00 (good season)
2009-11-01 00:00:00 (good season)
2009-11-02 00:00:00 (bad season)
2009-11-03 00:00:00 (bad season)
2009-11-04 00:00:00 (bad season)
2009-11-05 00:00:00 (bad season)
答案 0 :(得分:3)
循环,记录上一季:
$lastSeason = '';
foreach ($array as $date => $season)
{
if ($season != $lastSeason)
echo "Season changed on " . $date;
$lastSeason = $season;
}
答案 1 :(得分:1)
存储最后一次迭代的状态,并将其与当前状态进行比较。如果它们不同,请打印该项目:
$last = null;
foreach ($array as $val) {
if (preg_match('/^\d{4}-\d{2}\d{2} \d{2}:\d{2}:\d{2} \((good|bad) season\)$/', $val, $match)) {
if ($last != $match[1]) {
echo $val;
}
$last = $match[1];
}
}
答案 2 :(得分:1)
假设您的数组是一个数组数组:
if(count($array) > 0) {
$prev = $array[0]['season'];
foreach ($array as $row) {
if ($row['season'] != $prev) echo $row['date'];
$prev = $row['season'];
}
}