简体   繁体   中英

Sorting array of numbers into specific range

I have an array in PHP, Basically all I want to do is display the following array into ranges of 5. eg: 0-5, 6-10, 11-15, 16-20, 21-25 etc:

Array
(
    [0] => 00
    [1] => 01
    [2] => 02
    [3] => 03
    [4] => 04
)

I have looked at the range() function - but this seems to output the single numbers from inputting a range. I'm sure this is really simple - thanks in advance:

After using arraychunk() I get the following output:

Array
(
    [0] => Array
    (
        [0] => 48
        [1] => 46
        [2] => 44
        [3] => 42
        [4] => 40
    )

    [1] => Array
    (
        [0] => 39
        [1] => 38
        [2] => 37
        [3] => 36
        [4] => 35
    )

    [2] => Array
    (
        [0] => 34
        [1] => 33
        [2] => 32
        [3] => 31
        [4] => 30
    )

    [3] => Array
    (
        [0] => 29
        [1] => 28
        [2] => 27
        [3] => 26
        [4] => 25
    )
)

This in theory works as I asked - however, these are actually years so in the first array chunk I looking to output years 1-5. My original array of numbers doesn't contain every year. eg 1,3,4,6,7, not 1,2,3,4,5

如果我对您的理解正确,则可以使用array_chunk函数将数组拆分为多个块

print_r(array_chunk($input_array, 5));

Try this. Use str_pad().

$nums = range(0, 99);
foreach ($nums as $v) {
    $arr[] = str_pad($v, 2, '0',STR_PAD_LEFT);
}
$res = array_chunk($arr, 5);
print_r($res);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM