Php separates arrays by a specified number
/**
- * Separate arrays by the specified number.
- * @ Param array $ array the array to be split
- * @ Param int $ number of groupNum groups
- */
- Public function splitArray ($ array, $ groupNum ){
- If (empty ($ array) return array ();
// The total length of the array
- $ AllLength = count ($ array );
// Number
- $ GroupNum = intval ($ groupNum );
// Start position
- $ Start = 0;
// Number of elements in the divided array
- $ Enum = (int) ($ allLength/$ groupNum );
// Result set
- $ Result = array ();
If ($ enum> 0 ){
- // The part in the score group that can be divided 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 ++ ){
// Extract elements from the specified starting position and length in the original array and place them in the new array.
- $ Result [] = array_slice ($ firstArray, $ start, $ enum );
// Add the number of accumulated elements to the start position
- $ Start + = $ enum;
- }
- // Add the remaining part of the array to the first few items of the result set.
- $ 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;
- }
|