redbrad0 Posted November 29, 2007 Share Posted November 29, 2007 I have a list of ID's that I would like to compile a easy to read list of ID's. Instead of listing out the numbers like 143,144,145,146,147,148,..... I would like a easy to read list of the ID's grouped together like below. Does anyone have any suggestions? 143-160, 172-181 Quote Link to comment Share on other sites More sharing options...
Barand Posted November 29, 2007 Share Posted November 29, 2007 Put them into an array (explode() function) Loop through numbers checking current against next. If the difference is > 1, end current group and start a new group. Quote Link to comment Share on other sites More sharing options...
micah1701 Posted November 29, 2007 Share Posted November 29, 2007 <?php $numbers = array(); for($i=143; $i<=160; $i++){ $numbers[] = $i; } for($i=172; $i<=181; $i++){ $numbers[] = $i; } print_r($numbers); ?> Quote Link to comment Share on other sites More sharing options...
Barand Posted November 29, 2007 Share Posted November 29, 2007 try <?php $nums = '1,2,3,4,6,7,8,10,12,13,14,16'; $na = explode (',', $nums); $k = count ($na); $grp_start = $na[0]; echo $na[0]; for ($i=1; $i<$k; $i++) { if ($na[$i] - $na[$i-1] > 1) { if ($na[$i-1]==$grp_start) echo ', '; else echo '-', $na[$i-1], ', '; echo $na[$i]; $grp_start = $na[$i]; } } if ($na[$i-1] != $grp_start) echo '-', $na[$i-1]; // edit: finish of last group if needed ?> --> 1-4, 6-8, 10, 12-14, 16 Quote Link to comment Share on other sites More sharing options...
redbrad0 Posted November 30, 2007 Author Share Posted November 30, 2007 Thanks for the information. I used it to create the following function which needs a array passed to it. This way it will make sure the numbers are in the correct order. function DisplayFriendlyNumbers($NumbersArray) { $final = ""; if(is_array($NumbersArray)) { sort($NumbersArray); // Pack the Ticket #'s into a list $Numbers = ""; foreach ($NumbersArray as $id) $Numbers .= $id . ", "; $Numbers = rtrim($Numbers, ", "); $na = explode (',', $Numbers); $k = count ($na); $grp_start = $na[0]; $final .= $na[0]; for ($i=1; $i<$k; $i++) { if ($na[$i] - $na[$i-1] > 1) { if ($na[$i-1]==$grp_start) $final .= ', '; else $final .= '-' . trim($na[$i-1]) . ', '; $final .= trim($na[$i]); $grp_start = $na[$i]; } } if ($na[$i-1] != $grp_start) $final .= '-' . trim($na[$i-1]); // edit: finish of last group if needed } return $final; } Quote Link to comment 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.