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 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图2.0 版本点聚合中Marker的位置无法实时更新,如何解决呢?
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题