我开发了一个程序,但没有在这里设置任何逻辑。用PHP构建

时间:2015-12-04 06:01:31

标签: php

我开发了一个程序,但没有在这里设置任何逻辑。

实施例。我输入1,2,3,7,9然后结果显示为1-3,7,9。有人请帮助

2 个答案:

答案 0 :(得分:0)

将输入输入整数数组后,

<?php

$inputs = array(1, 2, 3, 5, 6, 7, 8, 10, 55, 56, 100);
$length = sizeof($inputs);

if($length > 1) {

    $current = 0;
    $next = 0;
    $group_start = $inputs[0];
    $group_end = 0;
    $output = array();

    for($i = 0; $i < $length - 1; $i++) {
        $current = $inputs[$i];
        $next = $inputs[$i + 1];
        if($current != $next - 1) { // if there is a break
            $group_end = $current;
            if($group_start == $group_end) {
                array_push($output, $group_start);
            }
            else {
                array_push($output, $group_start . " - " . $group_end);
            }
            $group_start = $next;
        }
    }

    //check for last element in inputs array
    if($group_start == $next) { // if there was a break
        array_push($output, $group_start);
    }
    else {
        array_push($output, $group_start . " - " . $next);
    }
    echo implode(", ", $output);
}

答案 1 :(得分:0)

关于此的一些内容对你有用..

$input = array(1,3,2,5,7,8);
sort($input);

$output = array();

foreach($input as $tmp){
    //initialize for first run
    if(!isset($start)) 
    {
        //get the first character and ignore the rest of the execution for the first number
        $start = $tmp;
        $prev = $tmp;
        continue;
    }
    //if the numbers are in series, get the number as previous
    if( $prev+1 == $tmp )
    {
        $prev = $tmp;
    }
    //else get the number, and reset our series
    else
    {
        $output[] = array($start,$prev);
        $start = $tmp;
        $prev = $tmp;
    }
}

    //one more time to battle last input not being properly processed
    $output[] = array($start,$prev);

print_r($output);