PHP separates arrays by specified number

Source: Internet
Author: User
  1. /**

  2. * Separates the array by the specified number
  3. * @param array $array to be split
  4. * Number of groups @param int $groupNum
  5. */
  6. Public Function Splitarray ($array, $groupNum) {
  7. if (empty ($array)) return array ();

  8. The total length of the array

  9. $allLength = count ($array);

  10. Number

  11. $groupNum = Intval ($groupNum);

  12. Start position

  13. $start = 0;

  14. The number of elements in the divided array

  15. $enum = (int) ($allLength/$groupNum);

  16. Result set

  17. $result = Array ();

  18. if ($enum > 0) {

  19. The portion of an array in which the number of elements is divisible into a fractional group.
  20. $firstLength = $enum * $GROUPNUM;
  21. $firstArray = Array ();
  22. for ($i =0; $i < $firstLength; $i + +) {
  23. Array_push ($firstArray, $array [$i]);
  24. Unset ($array [$i]);
  25. }
  26. for ($i =0; $i < $groupNum; $i + +) {

  27. From the original array of the specified start position and length of the intercept element into the new array

  28. $result [] = Array_slice ($firstArray, $start, $enum);

  29. Start position plus number of accumulated elements

  30. $start + = $enum;
  31. }
  32. The remainder of the array is added to the first few items of the result set, respectively
  33. $secondLength = $allLength-$firstLength;
  34. for ($i =0; $i < $secondLength; $i + +) {
  35. Array_push ($result [$i], $array [$i + $firstLength]);
  36. }
  37. }else{
  38. for ($i =0; $i < $allLength; $i + +) {
  39. $result [] = Array_slice ($array, $i, 1);
  40. }
  41. }
  42. return $result;
  43. }

Copy Code
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.