简体   繁体   中英

Split array into 4-element chunks then implode into strings

$array = [1, 2, 3, 4, 5, 6, 7, 8, 9];

我想要像这样的输出

['1, 2, 3, 4', '5, 6, 7, 8', '9'];

You can use array_chunk() to split your array into chunks of 4 items. Then array_map() to implode() each chunk:

$array = [1, 2, 3, 4, 5, 6, 7, 8, 9];
$chunk = array_chunk($array, 4);
var_dump(array_map(fn($item) => implode(', ', $item), $chunk));

Outputs:

array(3) {
  [0]=> string(7) "1, 2, 3, 4"
  [1]=> string(7) "5, 6, 7, 8"
  [2]=> string(1) "9"
}

you can do that

 const $array = [1, 2, 3, 4, 5, 6, 7, 8, 9]; const $chunk = $array.reduce((r,v,i)=> { if (!(i%4)) r.pos = r.resp.push(`${v}`) -1 else r.resp[r.pos] += `,${v}` return r }, { resp : [], pos:0 } ).resp console.log( $chunk )

For best efficiency in terms of time complexity, loop over the array only once. As you iterate, divide the index by 4 and "floor" or "truncate" the dividend to form grouping keys.

When a grouping key is encountered more than once, prepend the delimiting comma-space before appending the new string value to the group's string.

Code: ( Demo )

$array = [1, 2, 3, 4, 5, 6, 7, 8, 9];

foreach ($array as $i => $v) {
    $group = (int) ($i / 4);
    if (isset($result[$group])) {
        $result[$group] .= ", $v";
    } else {
        $result[$group] = "$v";
    }
}
var_export($result);

More concisely, you can split the array into 4-element rows and then implode those elements to form your delimited strings. This has more expensive time complexity because it iterates more times than the number of elements in the input array. ( Demo )

var_export(
    array_map(
        fn($v) => implode(', ', $v),
        array_chunk($array, 4)
    )
);

You could also consume the input array as you isolate 4 elements at a time with array_splice() , but this is probably the least advisable since it eventually erases all of the data in the input array. ( Demo )

$result = [];
while ($array) {
    $result[] = implode(', ', array_splice($array, 0, 4));
}
var_export($result);

Output from all above techniques:

array (
  0 => '1, 2, 3, 4',
  1 => '5, 6, 7, 8',
  2 => '9',
)

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