Php separates arrays by a specified number

Source: Internet
Author: User

Php separates arrays by a specified number

This article mainly introduces the php implementation of separating arrays by a specified number. For more information, see.

The Code is as follows:

/**

*

* 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;

}

 

 

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.