php split array into smaller even arrays

微笑、不失礼 提交于 2019-11-27 23:13:52

EDIT: There's array_chunk, which does just that.

Well, I didn't feel like debugging, so I wrote a version with array_reduce:

$pergroup = 2;
$redfunc = function ($partial, $elem) use ($pergroup) {
    $groupCount = count($partial);
    if ($groupCount == 0 || count(end($partial)) == $pergroup)
        $partial[] = array($elem);
    else
        $partial[$groupCount-1][] = $elem;

    return $partial;
};

$arr = array(1,2,3,4,5);

print_r(array_reduce($arr, $redfunc, array()));

gives

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
        )

    [1] => Array
        (
            [0] => 3
            [1] => 4
        )

    [2] => Array
        (
            [0] => 5
        )

)
zahoor
$sections = array_chunk(array('k', 'l', 'm', 'n', 'o'), 2);

It seems to me that the distribution of the remaining items is too complicated.

If you know how many items are missing ($Remainder), why don´t you just generate a remaining slice and pop-off items with array_pop() until it´s empty?

By the way, you can use that procedure for the whole array as well.

function split_array(&$array, $slices) {
  $result = array();
  $l = count($array)-1;
  for ($i=0; $i<=$l; $i++) {
    if ($i == 0  || $i % $slices == 0) $tmp = array();
    $tmp[] = $array[$i];
    if ($i == $l || $i % $slices == 1) $result[] = $tmp; 
  }
  return $result;
}

There's array_chunk, which does just that.

http://www.php.net/manual/en/function.array-chunk.php

[just making the salient part of Artefacto's answer more explicit]

array_chunk doesn't fill the arrays evenly unless the total number of elements is divisible by the number of chunks you want; the last chunk may be much smaller than the first (e.g. if you have seven elements and you split in to three chunks, you'll get arrays containing three, three and one element).

The following implementation will attempt to smooth this out so that the array sizes are more even if that's what you're after, e.g. if you have seven elements you'll get chunks arrays containing three, two and two elements instead. It's still not even, but it's more even. It falls back to using array_chunk if the count is evenly divisible by the number of columns, as that will be faster (especially if you have large arrays).

<?php
function array_group($array, $num)                                                
{                                                                           
    $num = (int) $num;                                                      
    if ($num < 1) {                                                         
        throw new \InvalidArgumentException('At least one group must be returned.');
    }                                                                       

    $count = count($array);                                                
    if ($count && $count % $num === 0) {                                    
        return array_chunk($array, $count / $num);                         
    }                                                                       

    $groups = [];                                                           
    $offset = 0;                                                            
    do {                                                                    
        $length   = ceil(($count - $offset) / $num);                
        $groups[] = array_slice($array, $offset, $length);                 
        $offset   += $length;                                               
    } while (--$num);                                                       

    return $groups;                                                         
} 

print_r(array_chunk(array(1, 2, 3, 4, 5, 6, 7), 3));
/* Produces
Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [1] => Array
        (
            [0] => 4
            [1] => 5
            [2] => 6
        )

    [2] => Array
        (
            [0] => 7
        )

) */

print_r(array_group(array(1, 2, 3, 4, 5, 6, 7), 3));
/* Produces
Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [1] => Array
        (
            [0] => 4
            [1] => 5
        )

    [2] => Array
        (
            [0] => 6
            [1] => 7
        )
) */

Try this a simple usage. When it finds empty string it splits the array into two arrays. One from beggining to empty string index. Other from empty string index to the last.
Note : Emty string is not included in both. it is used only for condition checking.

    $column[] = "id";
    $column[] = "name";
    $column[] = "email";
    $column[] = "password";
    $column[] = "";
    $column[] = "uid";
    $column[] = "uname";
    $column[] = "mname";
    $column[] = "lname";
    $column[] = "city";
    $column[] = "country";
    $column[] = "zip";
    $column[] = "cell";
    $column[] = "address";
    split_array($column);

function split_array($column)
{

    $total = count($column);
    $num = array_search('',$column);

    $split = $total - $num ;
    $outer_sql = array_slice( $column , - ($split) + 1);
    array_splice($column , $num);

    echo "<pre>";
    print_r($outer_sql);
    echo "</pre>";
    echo "<pre>";
    print_r($column);
    echo "</pre>";  

}

It is simple way to divide php array in two equal sections. and you can fetch all elements and values of both arrays using foreach easity

list($firstarray, $secondarray) = array_chunk($vorstand_two_column, ceil(count($all_array_contents) / 2));  

foreach($firstarray as $fa) {
.... Code ....
}

foreach($secondarray as $sa) {
.... Code ....
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!