note 75022 added to function.array-chunk
| From: | azspot at gmail dot com | Date: | Tue, 08 May 2007 23:53:07 +0000 |
| Subject: | note 75022 added to function.array-chunk | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-126345@lists.php.net to get a copy of this message | ||
Tried to use an example below (#56022) for array_chunk_fixed that would "partition" or
divide an array into a desired number of split lists -- a useful procedure for "chunking"
up objects or text items into columns, or partitioning any type of data resource. However, there
seems to be a flaw with array_chunk_fixed â for instance, try it with a nine item list and with
four partitions. It results in 3 entries with 3 items, then a blank array.
So, here is the output of my own dabbling on the matter:
<?php
function partition( $list, $p ) {
$listlen = count( $list );
$partlen = floor( $listlen / $p );
$partrem = $listlen % $p;
$partition = array();
$mark = 0;
for ($px = 0; $px < $p; $px++) {
$incr = ($px < $partrem) ? $partlen + 1 : $partlen;
$partition[$px] = array_slice( $list, $mark, $incr );
$mark += $incr;
}
return $partition;
}
$citylist = array( "Black Canyon City", "Chandler", "Flagstaff",
"Gilbert", "Glendale", "Globe", "Mesa", "Miami",
"Phoenix", "Peoria", "Prescott",
"Scottsdale", "Sun City", "Surprise", "Tempe",
"Tucson", "Wickenburg" );
print_r( partition( $citylist, 3 ) );
?>
Array
(
[0] => Array
(
[0] => Black Canyon City
[1] => Chandler
[2] => Flagstaff
[3] => Gilbert
[4] => Glendale
[5] => Globe
)
[1] => Array
(
[0] => Mesa
[1] => Miami
[2] => Phoenix
[3] => Peoria
[4] => Prescott
[5] => Scottsdale
)
[2] => Array
(
[0] => Sun City
[1] => Surprise
[2] => Tempe
[3] => Tucson
[4] => Wickenburg
)
)
----
Server IP: 69.39.81.135
Probable Submitter: 67.88.141.162
----
Manual Page -- http://www.php.net/manual/en/function.array-chunk.php
Edit -- https://master.php.net/note/edit/75022
Del: integrated -- https://master.php.net/note/delete/75022/integrated
Del: useless -- https://master.php.net/note/delete/75022/useless
Del: bad code -- https://master.php.net/note/delete/75022/bad+code
Del: spam -- https://master.php.net/note/delete/75022/spam
Del: non-english -- https://master.php.net/note/delete/75022/non-english
Del: in docs -- https://master.php.net/note/delete/75022/in+docs
Del: other reasons-- https://master.php.net/note/delete/75022
Reject -- https://master.php.net/note/reject/75022
Search -- https://master.php.net/manage/user-notes.php