Jump to content

How to group a list of years into a range?


Joey14

Recommended Posts

I am using PHP and I have an array of vehicles, often with a range of years. I basically want to collapse the duplicate entries (where it's the same make/model/engine except for the year) and convert the individual years into a range. As an example, instead of individual entries of 2001, 2002, 2003, it collapses into a single entry of 2001-2003, while being mindful that sometime's there are single entries with one year (see the first entry).

So, I want to convert this:

    Acura CL 2.2L 1997
    Acura CL 2.3L 1998
    Acura CL 2.3L 1999
    Acura CL 3.0L 1997
    Acura CL 3.0L 1998
    Acura CL 3.0L 1999
    Acura CL 3.2L 2001
    Acura CL 3.2L 2002
    Acura CL 3.2L 2003
    Acura Integra 1.6L 1986
    Acura Integra 1.6L 1987
    Acura Integra 1.6L 1988
    Acura Integra 1.6L 1989
    Acura Integra 1.7L 1992
    Acura Integra 1.7L 1993
    Acura Integra 1.8L 1990
    Acura Integra 1.8L 1991
    Acura Integra 1.8L 1992
    Acura Integra 1.8L 1993
    Acura Integra 1.8L 1994
    Acura Integra 1.8L 1995
    Acura Integra 1.8L 1996
    Acura Integra 1.8L 1997
    Acura Integra 1.8L 1998
    Acura Integra 1.8L 2000
    Acura Integra 1.8L 2001

to this:

    Acura CL 2.2L 1997
    Acura CL 2.3L 1998-1999
    Acura CL 3.0L 1997-1999
    Acura CL 3.2L 2001-2003
    Acura Integra 1.6L 1986-1989
    Acura Integra 1.7L 1992-1993
    Acura Integra 1.8L 1990-1998
    Acura Integra 1.8L 2000-2001

Any help would be HIGHLY appreciated! Thank you so much!

Something like this:

 

$cars = array();

foreach ($list as $car) {
  $year = substr($car, -4);
  $model = substr($car, 0, strlen($car) - 5);
  
  $cars[$model][] = $year;
}

foreach ($cars as $model => $years) {
  echo $model . ' ';
  if (count($years) == 1) {
    echo $years[0];
  } else {
    echo min($years) . '-' . max($years);
  }
  echo '<br>';
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.