doufei2662 2015-03-27 09:16
浏览 75
已采纳

将字符串列表拆分为类似长度的新列表

Say I have a list of 65 strings.
I need to split this single list into multiple "pools" that have a similar amount of strings.
The amount cannot be over 32.

In this list of 65, they're all ranked from 1st to 65th.

  • For a list of 65 strings, it'd split into one pool of 21, and two pools of 22.
  • For a list of 34 strings, it'd split into one pool of 18, and one pool of 18.
  • For a list of 115 strings, it'd split into one pool of 28, and three pools of 29.

And so on.

However, the new lists need to be fairly ranked.
In example it should be like so:

  • rank 1 in pool 1
  • rank 2 in pool 2
  • rank 3 in pool 3
  • rank 4 in pool 1
  • rank 5 in pool 2
  • rank 6 in pool 3

This way, rank 1 and rank 4, become rank 1 and 2 in their new list.
Same goes for the rest.

I'm thinking I'd need to use array_chunk in combination with a modulo operation, but I can't seem to wrap my head around it.

  • 写回答

2条回答 默认 最新

  • dtbam62840 2015-03-27 09:51
    关注

    This is not as difficult as it might seem:

    // settings
    $cellCount   = 115;
    $maxPoolSize = 32;
    
    // create test array with numbered strings
    $testArray = array_fill(1,$cellCount,'Cell ');
    foreach ($testArray as $key => $value) $testArray[$key] .= $key;
    
    // determine the number of pools needed
    $arraySize   = count($testArray);
    $poolCount   = ceil($arraySize/$maxPoolSize);
    
    // fill the pools
    $poolNo = 0;
    foreach ($testArray as $cell)
    {
      $poolArray[$poolNo][] = $cell;
      $poolNo++;
      if ($poolNo == $poolCount) $poolNo = 0;
    }
    
    // show result
    echo '<pre>';
    print_r($poolArray);
    echo '</pre>';
    

    I'm sure there are other solutions, but this seems to do the job.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 深度学习残差模块模型
  • ¥20 两个不同Subnet的点对点连接
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)