[英]Split array into separate arrays
I have an array $products
which contains a non-fixed number of elements. 我有一个数组
$products
,其中包含数量不固定的元素。
I need to split this array into 3 individual arrays. 我需要将此数组拆分为3个单独的数组。 The first two arrays should contain an equal number of elements and the last array may contain less.
前两个数组应包含相等数量的元素,而最后一个数组可以包含较少数量的元素。
So for example if $products
contains 16 elements, the output should be: 因此,例如,如果
$products
包含16个元素,则输出应为:
In the event that there are less than 3 elements in $products
, then the relevant arrays need to just return empty. 如果
$products
元素少于3个,则相关数组只需要返回空。
How can I do this? 我怎样才能做到这一点? I tried using
array_chunk()
but doesn't quite do what I want. 我尝试使用
array_chunk()
但并没有完全按照我的意愿进行。
$distributed = array_chunk($products, 3, true);
刚刚找到答案:
$distributed = array_chunk($products, (int)ceil(count($products)/3), true);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.