当前位置:Gxlcms > PHP教程 > PHP5入门之分组算法

PHP5入门之分组算法

时间:2021-07-01 10:21:17 帮助过:26人阅读

例子,把一组数据拆分为6组输出算法。 代码:

  1. $groupCount = 6; //组数
  2. $userIdList = array(1, 2, 3, 4, 5, 6, 7, 8, 9,10);
  3. $size = count($userIdList );
  4. $sizeGroupPer = floor($size / $groupCount );//每组被分配的个数
  5. $criticalValue = $size % $groupCount ; //临界值
  6. $startIndex = 0;
  7. $endIndex = 0;
  8. for ($i = 0; $i < $groupCount ; $i++ ) {
  9. if ($i < $critical) { //表示哪些组可以被多分配
  10. $endIndex = $startIndex + $sizeGroupPer + 1;
  11. } else {
  12. $endIndex = $startIndex + $sizeGroupPer ;
  13. } // bbs.it-home.org
  14. $strGroup = "";
  15. for ($j = $startIndex ; $j < $endIndex; $j++) {
  16. if (($j + 1) == $to) {
  17. $strGroup .= $arryData[$j];
  18. } else {
  19. $strGroup .= $arryData[$j].",";
  20. }
  21. }
  22. $startIndex = $endIndex;
  23. echo "第 ".$i." 组数据::".$strGroup;
  24. }

人气教程排行