Joey14 Posted January 4, 2014 Share Posted January 4, 2014 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 2001to 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-2001Any help would be HIGHLY appreciated! Thank you so much! Quote Link to comment https://forums.phpfreaks.com/topic/285082-how-to-group-a-list-of-years-into-a-range/ Share on other sites More sharing options...
ignace Posted January 4, 2014 Share Posted January 4, 2014 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>'; } Quote Link to comment https://forums.phpfreaks.com/topic/285082-how-to-group-a-list-of-years-into-a-range/#findComment-1463815 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.