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!

Link to comment
Share on other sites

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>';
}
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.