The PHP implementation separates the array by the specified number

Source: Internet
Author: User
Tags arrays

  This article mainly introduces the PHP implementation to separate the array by the specified number. Need friends can come to the reference, I hope to help you.

The code is as follows:/**  *   * separates the array by the specified number  * @param array $array the arrays to be split  * @param int $groupNum The number of groups to be divided  */ Public Function Splitarray ($array, $groupNum) {    if (empty ($array)) return array ();      //array Total length     $allLength = count ($array);      //number     $groupNum = Intval ($groupNum);      //Start position     $start = 0;      //partitioning of the number of elements in the array     $enum = (int) ($allLength/$groupNum);      //result set     $result = array ();       if ($enum > 0) {         //part of the number of elements in the array to be divisible into arrays in the group       & nbsp $firstLength = $enum * $GROUPNUM;         $firstArray = array ();         for ($i =0 $i < $firstLength $i + +) {            Array_push ($fir Starray, $array [$i]);             unset ($array [$i]);                for ($i =0 $i < $groupNum; $i + +) {             // From the specified start position and length intercept element in the original array to the new array             $result [] = Array_slice ($firstArray, $start, $enum);              //Start position plus number of cumulative elements             $start + = $enu M        }        //The remainder of the array is added to the first few items of the result set,    ,     $secondLength = $allLength-$firstLength;         for ($i =0 $i < $secondLength $i + +) {            Array_push ($re sult[$i], $array [$i + $firstLength]);        }    }else{        for ($i =0 $i < $allLength; $i + +) {  & nbsp         $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.