You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:30:57