php separates array by specified number

WBOY
Release: 2016-07-25 08:54:18
Original
1058 people have browsed it
  1. /**

  2. * Separate the array by the specified number
  3. * @param array $array The array to be divided
  4. * @param int $groupNum The number of groups to be divided
  5. */
  6. public function splitArray($array, $groupNum){
  7. if(empty($array)) return array();< ;/p>
  8. //Total length of the array

  9. $allLength = count($array);

  10. //Number of items

  11. $groupNum = intval($groupNum);< ;/p>
  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. //Divided The part of the array that can be divided evenly into the number of elements in the array
  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. < ;p> //Truncate elements from the specified starting position and length in the original array and put them into the new array
  28. $result[] = array_slice($firstArray, $start, $enum);

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

Copy code


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!