【问题标题】:Split an Array into 3 arrays [duplicate]将一个数组拆分为 3 个数组 [重复]
【发布时间】:2012-10-28 16:49:23
【问题描述】:

可能重复:
Slice an array into 4 other arrays

可以使用以下方法将一个数组拆分为 3 个较小的数组:

$things = array('...');    // an array containing 9 things
$things = array_chunk($things, count($things)/3);

问题:但是,当count($things) 数组中的项目数不能被3 平分时,我最终得到4 个更小的数组。例如,如果我在数组 $things 中有 10 个元素,将其输入到 array_chunk() 会得到 3 个包含 3 个元素的数组,以及包含 1 个元素的第 4 个数组。

如何将一个数组分成 3 个较小的数组,这样如果我遇到上面例子中的情况,我会得到

count($things[0]) == 4
count($things[1]) == 4
count($things[2]) == 2

基本上我正在做的是获取一个大数组并将其尽可能均等地显示为 3 列。它是按字母顺序排列的,所以顺序很重要。

【问题讨论】:

  • $n/3 向上取整,例如使用ceil()
  • 感谢 mario 成功了!我相信马里奥首先回答了它:)

标签: php


【解决方案1】:

试试ceil(count($things) / 3),这样分割点就会向上取整。对于 11 项数组,这会给你(比如说)4/4/3 而不是 3/3/3/2。

【讨论】:

    【解决方案2】:

    检查我在这个duplicate question上给出的答案,并将4更改为3

    $groups = array_chunk($all,(int)ceil(count($all)/3));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-18
      • 1970-01-01
      • 2012-01-01
      相关资源
      最近更新 更多