note 48268 added to function.array-chunk
| From: | phpm at nreynolds dot me dot uk | Date: | Fri, 17 Dec 2004 12:21:36 +0000 |
| Subject: | note 48268 added to function.array-chunk | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-81905@lists.php.net to get a copy of this message | ||
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;
}
?>
----
Manual Page -- http://www.php.net/manual/en/function.array-chunk.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+48268
Delete -- http://master.php.net/manage/user-notes.php?action=delete+48268&report=yes
Reason: bad code -- http://master.php.net/manage/user-notes.php?action=delete+48268&report=yes&reason=bad+code
Reason: spam -- http://master.php.net/manage/user-notes.php?action=delete+48268&report=yes&reason=spam
Reason: useless example -- http://master.php.net/manage/user-notes.php?action=delete+48268&report=yes&reason=useless+example
Reason: contains commercial links -- http://master.php.net/manage/user-notes.php?action=delete+48268&report=yes&reason=contains+commercial+links
Reason: useless note -- http://master.php.net/manage/user-notes.php?action=delete+48268&report=yes&reason=useless+note
Reject -- http://master.php.net/manage/user-notes.php?action=reject+48268&report=yes
Search -- http://master.php.net/manage/user-notes.php