douzhuo8312 2014-03-11 23:22
浏览 18
已采纳

将数组拆分为单独的数组

I have an array $products which contains a non-fixed number of elements.

I need to split this array into 3 individual arrays. 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:

  • Array 1 contains: 6 elements
  • Array 2 contains: 6 elements
  • Array 3 contains: 4 elements

In the event that there are less than 3 elements in $products, then the relevant arrays need to just return empty.

How can I do this? I tried using array_chunk() but doesn't quite do what I want.

$distributed = array_chunk($products, 3, true);

  • 写回答

1条回答 默认 最新

  • dshmkgq558192365 2014-03-11 23:27
    关注

    Just found the answer:

    $distributed = array_chunk($products, (int)ceil(count($products)/3), true);

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?