开发者

Reverse range-like functionality in php arrays

开发者 https://www.devze.com 2023-01-31 19:05 出处:网络
I have an array like this: array(0, 2, 4, 5, 6, 7, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99); and I want to get it as a the following string:

I have an array like this:

array(0, 2, 4, 5, 6, 7, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99);

and I want to get it as a the following string:

0, 2, 4-7, 90+

Any examples out there before I start to pull hairs from my head ?

Thanks.

UPDATE:

Here is the final solution I used after taking @Andy's code, and modifying it a bit.

function rangeArrayToString($rangeArray, $max = 99) {
    sort($rangeArray);
    $first = $last = null;
    $output = array();

    foreach ($rangeArray as $item) {
        if ($first === null) {
            $first = $la开发者_StackOverflowst = $item;
        } else if ($last < $item - 1) {
            $output[] = $first == $last ? $first : $first . '-' . $last;
            $first = $last = $item;
        } else {
            $last = $item;
        }
    }

    $finalAddition = $first;

    if ($first != $last) {
        if ($last == $max) {
            $finalAddition .= '+';
        } else {
            $finalAddition .= '-' . $last;
        }
    }

    $output[] = $finalAddition;

    $output = implode(', ', $output);
    return $output;
}


$first = $last = null;
$output = array();

foreach ($array as $item) {
    if ($first === null) {
        $first = $last = $item;
    } else if ($last < $item - 1) {
        $output[] = $first == $last ? $first : $first . '-' . $last;
        $first = $last = $item;
    } else {
        $last = $item;
    }
}

$output[] = $first == $last ? $first : $first . '+';
$output = join(', ', $output);


function makeRange($array, $last=array(), $done=array()){
    if ($array == array()) {
        return $done;
    }

    $h = $array[0]; 
    $t = array_slice($array, 1);

    if ($last == array()) {
        $last = array($array[0], $array[0]);
    }
    if ($t[0] == 1 + $last[1]) {
        return makeRange($t, array($last[0], $h+1), $done);
    }
    $done[] = $last;
    return makeRange($t, array(), $done);
}

print_r(makeRange(array(1,2,3,5,6,7, 9, 11,12,13,18)));

// Output 

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 3
        )

    [1] => Array
        (
            [0] => 5
            [1] => 7
        )

    [2] => Array
        (
            [0] => 9
            [1] => 9
        )

    [3] => Array
        (
            [0] => 11
            [1] => 13
        )

    [4] => Array
        (
            [0] => 18
            [1] => 18
        )

)

you could add a simple decorator to give the required 4-7 instead of array(4,7). This I left out because the view of the data should be seperate.

Hope that helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消