使用array_chunk基于另一个数组动态拆分数组

时间:2016-11-21 09:15:02

标签: php arrays

我试图以动态的方式拆分数组,比如在函数array_chunk上而不是第二个参数int $size,以允许添加像array different_sizes这样的数组

    $input_sub_arr = range('01', '15');
    $input_sub_array = array();
    foreach ($input_sub_arr as $answer) {
        $input_sub_array[] = 'answer-'.$answer;
    }
    var_Dump($input_sub_array);

$new_answer = array_chunk($input_sub_array, array(5, 6 , 2));
var_dump($new_answer);

1 个答案:

答案 0 :(得分:1)

即便这样做的目标是什么?你是说你要创建3个数组,一个有5个项目,后面跟一个有6个,后面有一个有2个?

function partition(array $values, array $sizes)
{
    $results = [];
    foreach ($sizes as $size) {
        $current = [];
        while (count($values) > 0 && count($current) < $size) {
            $current[] = array_unshift($values);
        }
        $results[] = $current;
    }
    return $results;
}

$result = partition($input_sub_arr, [5, 6, 2]);
// [['answer-01', 'answer-02', 'answer-03', 'answer-04', 'answer-05'], ['answer-06', 'answer-07', 'answer-08', 'answer-09', 'answer-10', 'answer-11'], ['answer-12', 'answer-13']]