首页 > 编程笔记 > PHP笔记

PHP array_chunk():分割数组

PHP array_chunk() 函数可以将一个数组分割成多个,其语法如下:

array array_chunk ( array $arr , int $size [, bool $preserve_keys = false ] )

参数说明:
array_chunk() 会将 arr 数组分割成多个子数组,每个子数组的元素个数由 size 决定。最后一个子数组的元素个数可能会少于 size 个。

返回值:返回一个由分割后的子数组构成的多维数组。

使用示例如下:
<?php
$arr1 = array("新宝库", "PHP教程", "https://www.xinbaoku.com/php/", "Java教程", "https://www.xinbaoku.com/java/", "Python教程", "https://www.xinbaoku.com/python/");
print_r( array_chunk($arr1, 3) );  //不保留原有键名
print_r( array_chunk($arr1, 3, true) );  //保留原有键名

$arr2 = array( 'fruits'=>array('Apple', 'banana', 'pear', 'orange'), 'animal', 'vehicle', 'architecture', 'food');
print_r( array_chunk($arr2, 3) );
print_r( array_chunk($arr2, 3, true) );
?>
执行以上程序的输出结果如下:

Array
(
    [0] => Array
    (
        [0] => 新宝库
        [1] => PHP教程
        [2] => https://www.xinbaoku.com/php/
    )
    [1] => Array
    (
        [0] => Java教程
        [1] => https://www.xinbaoku.com/java/
        [2] => Python教程
    )
    [2] => Array
    (
        [0] => https://www.xinbaoku.com/python/
    )
)

Array
(
    [0] => Array
    (
        [0] => 新宝库
        [1] => PHP教程
        [2] => https://www.xinbaoku.com/php/
    )
    [1] => Array
    (
        [3] => Java教程
        [4] => https://www.xinbaoku.com/java/
        [5] => Python教程
    )
    [2] => Array
    (
        [6] => https://www.xinbaoku.com/python/
    )
)

Array
(
    [0] => Array
    (
        [0] => Array
        (
            [0] => Apple
            [1] => banana
            [2] => pear
            [3] => orange
        )

        [1] => animal
        [2] => vehicle
    )
    [1] => Array
    (
        [0] => architecture
        [1] => food
    )
)

Array
(
    [0] => Array
    (
        [fruits] => Array
        (
            [0] => Apple
            [1] => banana
            [2] => pear
            [3] => orange
        )

        [0] => animal
        [1] => vehicle
    )
    [1] => Array
    (
        [2] => architecture
        [3] => food
    )
)

所有教程

优秀文章