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);

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

报告相同问题?

悬赏问题

  • ¥100 数字取证课程 关于FAT文件系统的操作
  • ¥15 如何使用js实现打印时每页设置统一的标题
  • ¥15 安装TIA PortalV15.1报错
  • ¥15 能把水桶搬到饮水机的机械设计
  • ¥15 Android Studio中如何把H5逻辑放在Assets 文件夹中以实现将h5代码打包为apk
  • ¥15 使用小程序wx.createWebAudioContext()开发节拍器
  • ¥15 关于#爬虫#的问题:请问HMDB代谢物爬虫的那个工具可以提供一下吗
  • ¥15 vue3+electron打包获取本地视频属性,文件夹里面有ffprobe.exe 文件还会报错这是什么原因呢?
  • ¥20 用51单片机控制急停。
  • ¥15 孟德尔随机化结果不一致