note 88833 modified in function.array-slice by thiago

From: Date: Tue, 10 Feb 2009 13:46:11 +0000
Subject: note 88833 modified in function.array-slice by thiago
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-150447@lists.php.net to get a copy of this message
I've written this array slicer that remains key association and subdivides all data into subarrays, I didn't profile this but I think it's faster then other implementations. By default you will split it in half or you can get more arrays returned. This can be very useful when you have an array structure of 47 items that needs to be divided into three (html) table columns. <?php /** * Split an array into $n sub-arrays and remain key associations. * * @param $array * The array structure which needs to be splitted. * @param $n * The number of sub-arrays the datastructure needs to * be spliced into. * @return * An array containing $n sub-arrays. */ function array_smartsplit($array, $n = 2) { $container = array_fill(0, $n, array()); $pointer = 0; foreach ($array as $k => $v) { $container[$pointer][$k] = $v; $pointer++; if ($pointer == $n) $pointer = 0; } return $container; } ?> --was-- I've written this array slicer that remains key association and subdivides all data into subarrays, I didn't profile this but I think it's faster then other implementations. By default you will split it in half or you can get more arrays returned. This can be very useful when you have an array structure of 47 items that needs to be divided into three (html) table columns. /** * Split an array into $n sub-arrays and remain key associations. * * @param $array * The array structure which needs to be splitted. * @param $n * The number of sub-arrays the datastructure needs to * be spliced into. * @return * An array containing $n sub-arrays. */ function array_smartsplit($array, $n = 2) { $container = array_fill(0, $n, array()); $pointer = 0; foreach ($array as $k => $v) { $container[$pointer][$k] = $v; $pointer++; if ($pointer == $n) $pointer = 0; } return $container; } http://php.net/manual/en/function.array-slice.php

« previous php.notes (#150447) next »