Home > php教程 > php手册 > php 算法之分割数组,不用array_chunk()

php 算法之分割数组,不用array_chunk()

WBOY
Release: 2016-06-21 08:47:24
Original
1483 people have browsed it

用php写算法分割数组,不用array_chunk();算法如下所示。

<?php
//$array 数组
//$size  每个数组的个数
//每个数组元素是否默认键值
function array_chunk_list($array, $size, $preserve_keys = false)
{
    reset($array);
    $i = 0;
    foreach ($array as $key => $value) {
        // 是否存在这个值
        if (! isset($newarray[$i])) {
            $newarray[$i] = array();
        }
        if (count($newarray[$i]) < $size) { // 先判断的问题
            if ($preserve_keys == false) {
                $newarray[$i][] = $value;
            } else {
                $newarray[$i][$key] = $value;
            }
        } else {
               $i++;
            if ($preserve_keys == false) {
                $newarray[$i][] = $value;
            } else {
                $newarray[$i][$key] = $value;
            }
        }
    }
    return $newarray;
}
  
  $array=array(1,2,3,4,5,6,7);
  print_r(array_chunk_list($array, 2,true));
Copy after login




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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template