php实现把数组按指定的个数分隔_PHP

WBOY
Release: 2016-06-01 11:55:54
Original
813 people have browsed it

复制代码 代码如下:
/**
 *
 * 把数组按指定的个数分隔
 * @param array $array 要分割的数组
 * @param int $groupNum 分的组数
 */
public function splitArray($array, $groupNum){
    if(empty($array)) return array();

    //数组的总长度
    $allLength = count($array);

    //个数
    $groupNum = intval($groupNum);

    //开始位置
    $start = 0;

    //分成的数组中元素的个数
    $enum = (int)($allLength/$groupNum);

    //结果集
    $result = array();

    if($enum > 0){

        //被分数组中 能整除 分成数组中元素个数 的部分
        $firstLength = $enum * $groupNum;
        $firstArray = array();
        for($i=0; $i            array_push($firstArray, $array[$i]);
            unset($array[$i]);
        }
        for($i=0; $i
            //从原数组中的指定开始位置和长度 截取元素放到新的数组中
            $result[] = array_slice($firstArray, $start, $enum);

            //开始位置加上累加元素的个数
            $start += $enum;
        }
        //数组剩余部分分别加到结果集的前几项中
        $secondLength = $allLength - $firstLength;
        for($i=0; $i            array_push($result[$i], $array[$i + $firstLength]);
        }
    }else{
        for($i=0; $i            $result[] = array_slice($array, $i, 1);
        }
    }
    return $result;
}

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!