有时您有一个数组并且需要将该数组分割成更小的数组,我通常会使用explode 或foreach 并进行一些自定义编码,但是PHP 中有一个更好的方法,它内置了一个名为array_chunk 的函数。

它接受 3 个参数:

  1. 数据数组
  2. 每个块的大小
  3. 保留键 – 当设置为 TRUE 键将被保留。默认为 FALSE,它将以数字方式重新索引块。

这是完美的,例如看看这个简单的例子:

//array of items
$items = ['Book', 'Mobile', 'Laptop', 'Monitor', 'Keys', 'Cards'];

//split the above array into multiple arrays containing 2 indexes in each.
$parts = array_chunk($items, 2);

//print out the results
echo '<pre>'; print_r($parts); echo '</pre>';

Returns:
Array
(
    [0] => Array
        (
            [0] => Book
            [1] => Mobile
        )

    [1] => Array
        (
            [0] => Laptop
            [1] => Monitor
        )

    [2] => Array
        (
            [0] => Keys
            [1] => Cards
        )

)

 

发表回复

您的电子邮箱地址不会被公开。