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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化