PHP: array_chunk - Manual

downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

array_combine array_change_key_case

Last updated: Sat, 27 Jan 2007

view this page in

# array_chunk

(PHP 4 >= 4.2.0, PHP 5)

array_chunk -- Разбить массив на части

## Описание

array array_chunk ( array input, integer size [, bool preserve_keys] )

Функция array_chunk() разбивает массив на несколько массивов размером `size` значений. Последний массив из полученных может содержать меньшее количество значений, чем указано. В качестве результата функция возвращает многомерный массив с индексами, начинающимися с нуля и элементами, которыми являются массивы, полученные в результате разбивки.

Если вы передадите значение `TRUE` в качестве необязательного параметра `preserve_keys`, PHP сохранит ключи из исходного массива. Если значение этого параметра равно `FALSE`, элементы результирующих массивов будут проиндексированы числами, начиная с нуля. По умолчанию используется значение `FALSE`.

Пример 1. Пример использования array_chunk()

`$input_array = array('a', 'b', 'c', 'd', 'e'); print_r(array_chunk($input_array, 2)); print_r(array_chunk($input_array, 2, TRUE));`

Результатом выполнения вышеприведенной программы будет:

    Array
    (
        [0] => Array
            (
                [0] => a
                [1] => b
            )

        [1] => Array
            (
                [0] => c
                [1] => d
            )

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

    )
    Array
    (
        [0] => Array
            (
                [0] => a
                [1] => b
            )

        [1] => Array
            (
                [2] => c
                [3] => d
            )

        [2] => Array
            (
                [4] => e
            )

    )

add a note User Contributed Notes
array_chunk
21-Mar-2006 04:19
`Here my array_chunk_values( ) with values distributed by lines (columns are balanced as much as possible) :
<?php
function array_chunk_vertical($data, $columns) {
$n = count($data) ;
$per_column = floor($n / $columns) ;
$rest = $n % $columns ;
// The map
$per_columns = array( ) ;
for ( $i = 0 ; $i < $columns ; $i++ ) {
$per_columns[$i] = $per_column + ($i < $rest ? 1 : 0) ;
}
$tabular = array( ) ;
foreach ( $per_columns as $rows ) {
for ( $i = 0 ; $i < $rows ; $i++ ) {
$tabular[$i][ ] = array_shift($data) ;
}
}
return $tabular ;
}
header('Content-Type: text/plain') ;
$data = array_chunk_vertical(range(1, 31), 7) ;
foreach ( $data as $row ) {
foreach ( $row as $value ) {
printf('[%2s]', $value) ;
}
echo "\r\n" ;
}
/*
Output :
[ 1][ 6][11][16][20][24][28]
[ 2][ 7][12][17][21][25][29]
[ 3][ 8][13][18][22][26][30]
[ 4][ 9][14][19][23][27][31]
[ 5][10][15]
*/
?>`
magick dit crow ot gmail dit com
16-Oct-2005 09:50
`Mistake key did not do what I thought. A patch.
function array_bucket($array,$bucket_size)// bucket filter
{
if (!is_array($array)) return false;
$buckets=array_chunk($array,$bucket_size);// chop up array into bucket size units
$I=0;
foreach ($buckets as $bucket)
{
$new_array[$I++]=array_sum($bucket)/count($bucket);
}
return $new_array;// return new array
}`
magick dit crow ot gmail dit com
15-Oct-2005 10:58
`This function takes each few elements of an array and averages them together. It then places the averages in a new array. It is used to smooth out data. For example lets say you have a years worth of hit data to a site and you want to graph it by the week. Then use a bucket of 7 and graph the functions output.
function array_bucket($array, $bucket_size) // bucket filter
{
if (!is_array($array)) return false; // no empty arrays
$buckets=array_chunk($array,$bucket_size); // chop up array into bucket size units
foreach ($buckets as $bucket) $new_array[key($buckets])=array_sum($bucket)/count($bucket);
return $new_array; // return new smooth array
}`
webmaster at cafe-clope dot net
20-Aug-2005 04:27
`based on the same syntax, useful about making columns :
<?php
function array_chunk_fixed($input, $num, $preserve_keys = FALSE) {
$count = count($input) ;
if($count)
$input = array_chunk($input, ceil($count/$num), $preserve_keys) ;
$input = array_pad($input, $num, array()) ;
return $input ;
}
$array = array(1, 2, 3, 4, 5) ;
print_r(array_chunk($array, 2)) ;
print_r(array_chunk_fixed($array, 2)) ;
?>
---- array_chunk : fixed number of sub-items ----
Array(
[0] => Array(
[0] => 1
[1] => 2
)
[1] => Array(
[0] => 3
[1] => 4
)
[2] => Array(
[0] => 5
)
)
---- array_chunk : fixed number of columns ----
Array(
[0] => Array(
[0] => 1
[1] => 2
[2] => 3
)
[1] => Array(
[0] => 4
[1] => 5
)
)`
cdblog at gmail dot com
21-May-2005 11:19
`<?php
/**
* @return array
* @author Cocol
* @desc use array_chunk with custom keys
* for more detail please visit http://php.clickz.cn/articles/array/array_chunk.html
*/
function array_chunk_custom($input_array = array(), $size = 0, $keys = array()) {
if (is_array($keys)) {
$values = array_values($input_array);
unset($input_array);
foreach ($keys as $key=>$val) {
$input_array[$val] = $values[$key];
}
}
$output_array = array_chunk($input_array,$size,1);
return $output_array;
}
$input_array = array('a', 'b', 'c', 'd', 'e','f','g','h');
$key_array = array('i','ii','iii','iv','v','vi','vii');
print_r(array_chunk_custom($input_array,2,$key_array));
?>
output:
Array
(
[0] => Array
(
[i] => a
[ii] => b
)
[1] => Array
(
[iii] => c
[iv] => d
)
[2] => Array
(
[v] => e
[vi] => f
)
[3] => Array
(
[vii] => g
)
)`
berndt at michael - berndt dot de
22-Apr-2005 08:22
`SplitAssoziativArray() without array_chunk()
http://www.michael-berndt.de/ie/tux/assoziativen_array_zerteilen.htm`
berndt at www dot michael-berndt dot de
10-Apr-2005 08:11
`split array without array_chunk()
http://www.michael-berndt.de/ie/tux/split_array.htm`
phpm at nreynolds dot me dot uk
17-Dec-2004 04:21
`array_chunk() is helpful when constructing tables with a known number of columns but an unknown number of values, such as a calendar month. Example:
<?php
$values = range(1, 31);
$rows = array_chunk($values, 7);
print "<table>\n";
foreach ($rows as $row) {
print "<tr>\n";
foreach ($row as $value) {
print "<td>" . $value . "</td>\n";
}
print "</tr>\n";
}
print "</table>\n";
?>
Outputs:
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
The other direction is possible too, with the aid of a function included at the bottom of this note. Changing this line:
$rows = array_chunk($values, 7);
To this:
$rows = array_chunk_vertical($values, 7);
Produces a vertical calendar with seven columns:
1 6 11 16 21 26 31
2 7 12 17 22 27
3 8 13 18 23 28
4 9 14 19 24 29
5 10 15 20 25 30
You can also specify that $size refers to the number of rows, not columns:
$rows = array_chunk_vertical($values, 7, false, false);
Producing this:
1 8 15 22 29
2 9 16 23 30
3 10 17 24 31
4 11 18 25
5 12 19 26
6 13 20 27
7 14 21 28
The function:
<?php
function array_chunk_vertical($input, $size, $preserve_keys = false, $size_is_horizontal = true)
{
$chunks = array();
if ($size_is_horizontal) {
$chunk_count = ceil(count($input) / $size);
} else {
$chunk_count = $size;
}
for ($chunk_index = 0; $chunk_index < $chunk_count; $chunk_index++) {
$chunks[] = array();
}
$chunk_index = 0;
foreach ($input as $key => $value)
{
if ($preserve_keys) {
$chunks[$chunk_index][$key] = $value;
} else {
$chunks[$chunk_index][] = $value;
}
if (++$chunk_index == $chunk_count) {
$chunk_index = 0;
}
}
return $chunks;
}
?>`
mick at vandermostvanspijk dot nl
07-Apr-2004 03:02
`[Editors note: This function was based on a previous function by gphemsley at nospam users dot sourceforge.net]
For those of you that need array_chunk() for PHP < 4.2.0, this function should do the trick:
<?php
if (!function_exists('array_chunk')) {
function array_chunk( $input, $size, $preserve_keys = false) {
@reset( $input );
$i = $j = 0;
while( @list( $key, $value ) = @each( $input ) ) {
if( !( isset( $chunks[$i] ) ) ) {
$chunks[$i] = array();
}
if( count( $chunks[$i] ) < $size ) {
if( $preserve_keys ) {
$chunks[$i][$key] = $value;
$j++;
} else {
$chunks[$i][] = $value;
}
} else {
$i++;
if( $preserve_keys ) {
$chunks[$i][$key] = $value;
$j++;
} else {
$j = 0;
$chunks[$i][$j] = $value;
}
}
}
return $chunks;
}
}
?>`
add a note
array_combine array_change_key_case

Last updated: Sat, 27 Jan 2007
show source | credits | stats | sitemap | contact | advertising | mirror sites
Copyright © 2001-2007 The PHP Group
All rights reserved.
This mirror generously provided by: Yahoo! Inc.
Last updated: Sat Mar 10 09:32:46 2007 PST