Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在php中将数组划分为特定大小?_Php_Arrays_Chunks - Fatal编程技术网

如何在php中将数组划分为特定大小?

如何在php中将数组划分为特定大小?,php,arrays,chunks,Php,Arrays,Chunks,我有一组数字来定义每个块的大小。如何根据这些大小对数组进行分块 例如,假设块大小为2、3和2,输入数组大小为7: array( 0 => 'a', 1 => 'f', 2 => 'j', 3 => 'r', 4 => 'c', 5 => 'j', 6 => 'd', ) 我希望上面数组中的前2个元素分块到它们自己的数组中,接下来的3个元素分块到它们自己的数组中,最后2个元素分块到它们自己的数组中。

我有一组数字来定义每个块的大小。如何根据这些大小对数组进行分块

例如,假设块大小为2、3和2,输入数组大小为7:

array(
    0 => 'a',
    1 => 'f',
    2 => 'j',
    3 => 'r',
    4 => 'c',
    5 => 'j',
    6 => 'd',
)
我希望上面数组中的前2个元素分块到它们自己的数组中,接下来的3个元素分块到它们自己的数组中,最后2个元素分块到它们自己的数组中。这将产生以下输出:

// first 2 elements:
array(
    0 => 'a',
    1 => 'f',
)

// next 3 elements:
array(
    0 => 'j',
    1 => 'r',
    2 => 'c',
)

// last 2 elements:
array(
    0 => 'j',
    1 => 'd',
)
我的实际输入数组有64个元素,我想按照大小7、9、11、16、9和12的精确顺序将其分块。

  • 循环浏览您的数据
  • 在变量中保留当前区块计数长度
  • 保持递减计数并将所有循环元素添加到临时数组
  • 如果计数达到
    0
    ,则将当前区块(如临时数组中的)添加到结果中,并继续移动到下一个区块
  • 下面的代码也适用于不规则的块大小或数据大小
片段:

<?php

$chunks_size = [7,9,11,16,9,12];
$data = ['a','f','j', 'r', 'c', 'j','d'];

$result = [];
$chunk_ptr = 0;
$count = $chunks_size[$chunk_ptr];
$temp = [];

foreach($data as $index => $val){
    $count--;
    $temp[] = $val;
    if($count == 0){
        $result[] = $temp;
        $temp = [];
        if(++$chunk_ptr == count($chunks_size)){
            $count = PHP_INT_MAX; // Set it to a higher value or any negative value(all remaining goes into the last chunk)
        }else{
            $count = $chunks_size[$chunk_ptr];   
        }
    }
}

if(count($temp) > 0) $result[] = $temp;


print_r($result);

您可以创建一个函数来为您的阵列进行分区。您可以先传入数组,然后传入所需的块

function partition($arr, ...$chunks) {
    $res = [];
    foreach($chunks as $n)
        $res[] = array_splice($arr, 0, $n);
    return $res;
}

$arr = ['a', 'f', 'j', 'r', 'c', 'j', 'd'];
print_r(partition($arr, 2, 3, 2));
分区通过使用进行,这将在适当的位置更改阵列。每次调用
array\u splice()。当您获取给定块的第一个
$n
元素时,也会将它们从数组中删除

输出:

Array
(
    [0] => Array
        (
            [0] => a
            [1] => f
        )

    [1] => Array
        (
            [0] => j
            [1] => r
            [2] => c
        )

    [2] => Array
        (
            [0] => j
            [1] => d
        )

)
见现场示例