php separates array by specified number
Release: 2016-07-25 08:54:18
Original
1105 people have browsed it
-
-
/** - * 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
|
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
Latest Articles by Author
-
2024-10-22 09:46:29
-
2024-10-13 13:53:41
-
2024-10-12 12:15:51
-
2024-10-11 22:47:31
-
2024-10-11 19:36:51
-
2024-10-11 15:50:41
-
2024-10-11 15:07:41
-
2024-10-11 14:21:21
-
2024-10-11 12:59:11
-
2024-10-11 12:17:31