tags:

views:

40

answers:

3

Let's say I have an array with dates and seasons, there is one entry for each day. I would like to print the array row only when the season value is changing.

the array look like that:

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)

+3  A: 

Loop through, keeping a record of the last season:

$lastSeason = '';

foreach ($array as $date => $season)
{
    if ($season != $lastSeason)
        echo "Season changed on " . $date;

    $lastSeason = $season;
}
Greg
+1  A: 

Store the state of the last iteration and compare it to the state of the current. If they differ, print the item:

$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];
    }
}
Gumbo
why use complex regexes for such a simple problem?
knittl
at least, it looks cool
mnml
+1  A: 

assuming your array is an array of arrays:

if(count($array) > 0) {
  $prev = $array[0]['season'];

  foreach ($array as $row) {
    if ($row['season'] != $prev) echo $row['date'];

    $prev = $row['season'];
  }
}
knittl