PHP如何将数组按12个元素分组并适配任意长度?
How to Split a PHP Array into Groups of 12 Elements (Dynamic for Any Length)
Oh, this is a perfect use case for PHP's built-in array_chunk() function—it’s designed exactly for splitting arrays into chunks of a specified size, and it handles any array length automatically, including when the total number of elements isn’t a multiple of your chunk size.
Here's how to implement it:
First, start with your original array:
$array = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm'];
Then use array_chunk() to split it into groups of 12 elements:
$rows = array_chunk($array, 12);
What this does:
- The first parameter is your target array.
- The second parameter is the size of each chunk (12 in this case).
- The optional third parameter (default is
false) lets you preserve the original array's keys if needed—for most indexed arrays like your example, you can leave this out.
Result:
If you print the $rows array, you’ll get exactly what you’re looking for:
// $rows[0] = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l']; // $rows[1] = ['m'];
It works for any array length:
- If your array has 24 elements, you’ll get two chunks of 12.
- If it has 15 elements, you’ll get one chunk of 12 and one chunk of 3.
- If it has fewer than 12 elements, you’ll get a single chunk with all the elements.
This function is efficient, clean, and requires no manual looping or counting—PHP handles all the heavy lifting for you.
内容的提问来源于stack exchange,提问作者Juan José González
相关产品推荐
相关产品推荐

