PDA

View Full Version : Array implosion question

toddandrae
01-02-2008, 08:28 PM
Let's say I have an array with values 1,2,3,5,7 or 1,3,4,5 and I wanted to change this to a string that would read 1-3,5,7 or 1,3-5. I am currently at a loss of ideas on how to accomplish this. If someone could just throw up some psuedo code I could probably go from there.

dumpfi
01-02-2008, 09:59 PM
<?php
/**
signature
array getRanges( array )

splits up the array into integer ranges, where each range is an array with the start and end of a range as values (in this order)
*/
function getRanges(\$array)
{
reset(\$array);

\$ranges = array();

if(FALSE !== key(\$array))
{
\$rStart = \$rEnd = current(\$array);
\$cur = next(\$array);

while(NULL !== key(\$array))
{
if(\$cur != \$rEnd + 1)
{
\$ranges[] = array(\$rStart, \$rEnd);
\$rStart = \$rEnd = \$cur;
}
else
{
++\$rEnd;
}
\$cur = next(\$array);
}

\$ranges[] = array(\$rStart, \$rEnd);
}
return \$ranges;
}
/**
signature
string stringRanges( array )

returns a string representation of the integer ranges of the values in the given array
*/
function stringRanges(\$array)
{
\$str = '';
foreach(getRanges(\$array) as \$range)
{
\$str .= ((\$range[0] == \$range[1]) ?
\$range[0] :
\$range[0].'-'.\$range[1]).',';
}
return substr(\$str, 0, -1);
}

\$array1 = array(1,2,3,5,7,8,9,10,12);

echo 'array('.implode(',', \$array1).') = ';
echo stringRanges(\$array1);
?>dumpfi

kbluhm
01-03-2008, 02:36 AM
function get_ranges( \$array )
{
sort( \$array );
\$key = 0;
\$ranges[\$key][] = reset( \$array );
while ( \$curr = next( \$array ) )
{
\$prev = prev( \$array );
next( \$array );
if ( \$curr - 1 == \$prev )
{
\$ranges[\$key][] = \$curr;
}
else
{
\$ranges[++\$key][] = \$curr;
}
}
\$return = array();
foreach ( \$ranges as \$k => \$v )
{
\$return[\$k] = reset( \$v );
if ( count( \$v ) > 1 )
{
\$return[\$k] .= '-' . end( \$v );
}
}
return implode( ', ', \$return );
}

\$array = array( 1, 2, 3, 5, 6, 8, 9, 10, 11, 12, 16, 18, 19, 20, 25 );

echo get_ranges( \$array ); // 1-3, 5-6, 8-12, 16, 18-20, 25