How to group numbers in ranges using PHP

别说谁变了你拦得住时间么 提交于 2020-06-14 07:21:52

问题


Let's say that I have the following sequence of numbers in an array:

$numbers = array(1,3,2,23,24,25,26, 8)

How can I print them in ranges, for instance:

The numbers are 1-3, 23-26, 8.


回答1:


Here's a simple version, creating groups containing your ranges

<?php
$numbers = array(1,3,2,23,24,25,26,8);
sort($numbers);
$groups = array();

for($i = 0; $i < count($numbers); $i++)
{
    if($i > 0 && ($numbers[$i - 1] == $numbers[$i] - 1))
        array_push($groups[count($groups) - 1], $numbers[$i]);
    else // First value or no match, create a new group
        array_push($groups, array($numbers[$i])); 
}

foreach($groups as $group)
{
    if(count($group) == 1) // Single value
        echo $group[0] . "\n";
    else // Range of values, minimum in [0], maximum in [count($group) - 1]
        echo $group[0] . " - " . $group[count($group) - 1] . "\n";
}

The output is

1 - 3
8
23 - 26

Now, if the order of your ranges is important, like you described in your question, you can still sort your groups... from what I can see, you want the ranges first followed by the single values? This can be done by adding

function groupRanges($a, $b)
{
    if(count($a) == 1)
        if(count($b) == 1)
            return 0; // equal
        else
            return 1; // so $b is considered less than

    if(count($b) == 1)
        return -1; // so $a is considered less than

    return 0; // both are ranges, keep them there... could be adjusted to compare the size of each range
}

usort($groups, "groupRanges");

right before the foreach and the output becomes:

1 - 3
23 - 26
8



回答2:


$numbers = array(1,3,2,23,24,25,26,8);

$result = array();

$sorted = $numbers;
sort($sorted);

$current = null;
foreach ($sorted as $v) {
    if (is_null($current)) {
        $current = array($v, $v);
    } else {
        if ($current[1] + 1 == $v) {
            $current[1] = $v;
        } else {
            $result[] = $current;
            $current = array($v, $v);
        }
    }
}

$result[] = $current;

$arranged = array();

foreach ($numbers as $v) {
    foreach ($result as $k => $r) {
        if ($v >= $r[0] && $v <= $r[1]) {
            $arranged[] = $r;
            unset($result[$k]);
            break;
        }
    }
}

var_dump($arranged);

http://ideone.com/i2YGod




回答3:


I know I'm a little late to the party, but I had to do it.

<?php
$numbers = array(1,3,2,23,24,25,26,8);
sort($numbers);
$x=0;
$output = array();
foreach($numbers as $k=>$n){
    if(isset($numbers[$k+1]) && $numbers[$k+1]==$n+1){
        $output[$x][]=$n;
    }elseif(isset($output[$x][count($output[$x])-1]) && $output[$x][count($output[$x])-1]+1==$n){
        $output[$x][]=$n;
    }else{
        $x++;
        $output[$x][] = $n;
        $x++;
    }
}
foreach($output as $o){
    echo $o[0];
    if(isset($o[count($o)-1]) && $o[count($o)-1]!=$o[0]){
        echo ' - '.$o[count($o)-1];
    }
    echo '<br>';
}?>



回答4:


Could not post this yesterday, so I'm very late. Thought it was elegant enough to share it.

<?php

$numbers = array(1, 3, 2, 23, 24, 25, 26, 8);
sort($numbers);
$result = array();

while (count($numbers) > 0)
{
    $begin = reset($numbers);
    $end = array_shift($numbers);

    while (in_array($end + 1, $numbers))
    {
        $end = array_shift($numbers);
    }
    $beginAndEnd = array_unique(array($begin, $end));
    $result[] = implode('-', $beginAndEnd);
}
var_dump($result);
?>



回答5:


First sort the array, say array A. Then do a binary search on it. Say the array is of size n:

take A[n/2], the element at n/2.

if A[n/2]-A[n/4] = n/2-n/4, then A[n/2] and A[n/4] are in the same group-- skip A[3n/8] and check A[n/8] to see whether A[n/2]-A[n/8] = n/2-n/8.

if A[n/2]-A[n/4] != n/2-n/4, then you've got two groups at hand-- one that has A[n/2] in and the other that has A[n/4] in. check A[n/8] to see whether it is in the same group as A[n/4]. Check A[3/8] to see whether it is in the same group as A[n/2], if not, whether in group of A[n/4].

You can also combine it with the sort algorithm but i don't think it's worth it. This is fast-- in logarithmic time and is modular.




回答6:


$sorted = $numbers; 
sort($sorted);
$sorted[] = null;  # add a null so the last iteration stores the final range
$ranges = array();
$end = null;
$start = null;

foreach ($sorted as $x) {
    if ($start === null) {
        # first iteration.  New range, but there's no previous one to mention
        $start = $x;
    }
    elseif ($x !== $end + 1) {
        # non-contiguous values == new range.
        # squirrel away the one we were just working on, and start fresh
        $ranges[] = ($start === $end) ? "$start" : "$start-$end";
        $start = $x;
    }
    $end = $x;
}

$ranges_str = implode(', ', $ranges);



回答7:


function get_ranges($numbers) {
sort($numbers);
$ranges=array();
while(current($numbers)){
$start=current($numbers);
$next=next($numbers);
$current=$start;
while( ($next-$current)==1){
    $current=$next;
    $next=next($numbers);
}
$ranges[]=array('start'=>$start,'end'=>$current);
}

return $ranges;

}


来源:https://stackoverflow.com/questions/13592547/how-to-group-numbers-in-ranges-using-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!