note 98494 deleted from function.array-merge by danbrown

From: Date: Fri, 18 Jun 2010 15:12:27 +0000
Subject: note 98494 deleted from function.array-merge by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-170245@lists.php.net to get a copy of this message
Note Submitter: twardy ---- In response to some array_interlace functions which have been posted here; I needed a function that operates on a single array and interlaces it, while slicing into chunks, so here it is. $array = single array passed to the function (for example an array of objects from a DB query) $chunks = number of chunks to be sliced to (for example 3 columns) $preserveKeys = self explainatory returns an arrays of interlaced chunks function array_chunks_interlace( $array = array(), $chunks = 3, $preserveKeys = FALSE ) { if( empty($array) || count($array) == 1 || $chunks <= 1 ) return $array; $result = array(); $counter = 0; for( $i=0;$i<count($array);$i++ ) { for( $j=0;$j<$chunks;$j++ ) { if( isset($array[$counter+$j]) ) { if( $preserveKeys === TRUE ) ${'chunk'.($j+1)}[$counter+$j] = $array[$counter+$j]; else ${'chunk'.($j+1)}[] = $array[$counter+$j]; } } $counter += $chunks; } $result = array(); for( $c=0;$c<$chunks;$c++ ) if( isset(${'chunk'.($c+1)}) ) $result[$c] = ${'chunk'.($c+1)}; return $result; }

« previous php.notes (#170245) next »