简体   繁体   中英

PHP: Split an array into diffrent size chunks based on values from another array

Is there a neat way to split array into chunks based on length from another array?

$start = range(0,30);
$length = array(3,7,2,12,6);

$target = array([0]=>array(0,1,2),
                [1]=>array(4,5,6,7,8,9,10),
                [2]=>array(11,12),
                [3]=>array(13,14,15,16,17,18,19,20,21,22,23,24),
                [4]=>array(25,26,27,28,29,30));

Using array_splice :

$target = array(); // or use []  in PHP 5.4
foreach($length as $i) {
    $target[] = array_splice($start, 0, $i);
}

Try it.

Be advised, this changes $start !

This is very easily accomplished with the following:

Code:

$target = array();
$offset = 0;

foreach ($length as $lengthValue) {
    $target[] = array_slice($start, $offset, $lengthValue);
    $offset += $lengthValue;
}
var_dump($target);

Explanation:

What you are doing here is using the array_slice() method (very similar to the substr ) to extract the portion of the array and then inserting it into the target array. Incrementing the offset each time allows the function to remember which one to use next time.

I think the The array_chunk() function may do it. Here is more info about it http://php.net/manual/en/function.array-chunk.php

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