https://codereview.stackexchange.com/questions/80080/aggregate-array-values-into-ranges
// Output:
// Array (
// [0] => Array ( [0] => 1, [1] => 2, [2] => 3, [3] => 4, [4] => 5, [5] => 6 )
// [1] => Array ( [0] => 10, [1] => 11, [2] => 12, [3] => 13 )
// [2] => Array ( [0] => 20 )
// [3] => Array ( [0] => 24 )
// )
static function GetRanges1( $aNumbers ) {
$aNumbers = array_unique( $aNumbers );
sort( $aNumbers );
$aGroups = array();
for( $i = 0; $i < count( $aNumbers ); $i++ ) {
if( $i > 0 && ( $aNumbers[$i-1] == $aNumbers[$i] - 1 ))
array_push( $aGroups[count($aGroups)-1], $aNumbers[$i] );
else
array_push( $aGroups, array( $aNumbers[$i] ));
}
return $aGroups;
}
// Output: Array ( [0] => 1-6, [1] => 10-13, [2] => 20, [3] => 24 )
static function GetRanges2( $aNumbers ) {
$aNumbers = array_unique( $aNumbers );
sort( $aNumbers );
$aGroups = array();
for( $i = 0; $i < count( $aNumbers ); $i++ ) {
if( $i > 0 && ( $aNumbers[$i-1] == $aNumbers[$i] - 1 ))
array_push( $aGroups[count($aGroups)-1], $aNumbers[$i] );
else
array_push( $aGroups, array( $aNumbers[$i] ));
}
$aRanges = array();
foreach( $aGroups as $aGroup ) {
if( count( $aGroup ) == 1 )
$aRanges[] = $aGroup[0];
else
$aRanges[] = $aGroup[0] . '-' . $aGroup[count($aGroup)-1];
}
return $aRanges;
}
// Output: 1~6,10~13,20,24
static function GetRanges3( $aNumbers, $headChar='' ) {
$aNumbers = array_unique( $aNumbers );
sort( $aNumbers );
$aGroups = array();
for( $i = 0; $i < count( $aNumbers ); $i++ ) {
if( $i > 0 && ( $aNumbers[$i-1] == $aNumbers[$i] - 1 ))
array_push( $aGroups[count($aGroups)-1], $aNumbers[$i] );
else
array_push( $aGroups, array( $aNumbers[$i] ));
}
$aRanges = array();
foreach( $aGroups as $aGroup ) {
if( count( $aGroup ) == 1 )
$aRanges[] = $headChar.$aGroup[0];
else
$aRanges[] = $headChar.$aGroup[0] . '~' . $headChar.$aGroup[count($aGroup)-1];
}
return implode( ',', $aRanges );
}