PHP implements separating arrays by specified number_PHP tutorial

WBOY
Release: 2016-07-13 10:25:04
Original
828 people have browsed it

Copy code The code is as follows:

/**
*
* Separate the array by the specified number
* @param array $array The array to be divided
* @param int $groupNum The number of groups
*/
public function splitArray($array, $groupNum){
if(empty($array)) return array();

//The total length of the array
$allLength = count($array);

//Number
$groupNum = intval($groupNum);

//Starting position
$start = 0;

//The number of elements in the divided array
$enum = (int)($allLength/$groupNum);

//Result set
$result = array();

if($enum > 0 ){

//The part of the divided 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]);                                                                                                                              i=0; $i<$groupNum; $i++){

                                                                                                                                                                                                                                          //Intercept elements from the specified starting position and length in the original array and put them into the new array. $firstArray, $start, $enum);

//The starting position plus the number of accumulated elements
加到结果集的前几项中
        $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;
}






http://www.bkjia.com/PHPjc/825231.html

www.bkjia.com

true

TechArticleCopy the code as follows: /*** * 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($arr...
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!