Php dizilerin Ters aralığı gibi işlevsellik

0 Cevap php


I have an array like this:

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

ve ben şu dize olarak almak istiyorum:

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 = $last = $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;
}

0 Cevap