Question

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.

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!

Was it helpful?

Solution

You can iterate on the names, and get the year, and store the information in a map

<?

foreach($models as $model){
  $type = substr($model, 0, -5);
  $year = substr($model, -4);
  if (!isset($results[$type])) {
    $results[$type] = array('min'=> $year, 'max'=>$year);
  } else {
    $results[$type]['min']=min($results[$type]['min'], $year);
    $results[$type]['max']=max($results[$type]['max'], $year);
  }
}

foreach($results as $type=>$years){
  if ($years['min']==$years['max']){
    $years_string = $years['min'];
  } else {
    $years_string = $years['min'],'-',$years['max'];
  }
  echo $type,' ', $years_string, "\n";

}

?>

Check this fiddle: http://codepad.org/kOe5pi1S

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top