-
-
/** - * Separate the array by the specified number
- * @param array $array The array to be divided
- * @param int $groupNum The number of groups to be divided
- */
- public function splitArray($array, $groupNum){
- if(empty($array)) return array();< ;/p>
//Total length of the array
- $allLength = count($array);
//Number of items
- $groupNum = intval($groupNum);< ;/p>
//Start position
- $start = 0;
//The number of elements in the divided array
- $enum = (int)($allLength/ $groupNum);
//Result set
- $result = array();
if($enum > 0){
- //Divided The part of the array that can be divided evenly into the number of elements in the array
- $firstLength = $enum * $groupNum;
- $firstArray = array();
- for($i=0; $i<$firstLength; $i++){
- array_push ($firstArray, $array[$i]);
- unset($array[$i]);
- }
- for($i=0; $i<$groupNum; $i++){
- < ;p> //Truncate elements from the specified starting position and length in the original array and put them into the new array
- $result[] = array_slice($firstArray, $start, $enum);
- $start += $enum;
- }
- //The remaining parts of the array are added to the first few items of the result set respectively
- $secondLength = $allLength - $firstLength;
- for ($i=0; $i<$secondLength; $i++){
- array_push($result[$i], $array[$i + $firstLength]);
- }
- }else{
- for($i=0 ; $i<$allLength; $i++){
- $result[] = array_slice($array, $i, 1);
- }
- }
- return $result;
- }
-
Copy code
|