Split array into a specific number of chunks
You can try
$input_array = array(
'a',
'b',
'c',
'd',
'e'
);
print_r(partition($input_array, 4));
Output
Array
(
[0] => Array
(
[0] => a
[1] => b
)
[1] => Array
(
[0] => c
)
[2] => Array
(
[0] => d
)
[3] => Array
(
[0] => e
)
)
Function Used
/**
*
* @param Array $list
* @param int $p
* @return multitype:multitype:
* @link http://www.php.net/manual/en/function.array-chunk.php#75022
*/
function partition(Array $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;
}
So many complex answers here. I'll post my simple solution :)
function splitMyArray(array $input_array, int $size, $preserve_keys = null): array
{
$nr = (int)ceil(count($input_array) / $size);
if ($nr > 0) {
return array_chunk($input_array, $nr, $preserve_keys);
}
return $input_array;
}
Usage:
$newArray = splitMyArray($my_array, 3);
More details here: https://zerowp.com/split-php-array-in-x-equal-number-of-elements/
Divide the size of the array with the number of chunks you want and supply that as the size of each chunk.
function array_chunks_fixed($input_array, $chunks=3 /*Default chunk size 3*/) {
if (sizeof($input_array) > 0) {
return array_chunk($input_array, intval(ceil(sizeof($input_array) / $chunks)));
}
return array();
}
And call it like this:
array_chunks_fixed($myarray, 2); //override the default number of '3'
This what i write and work well print_r(array_divide($input,3));
function array_divide($array, $segmentCount) {
$dataCount = count($array);
if ($dataCount == 0) return false;
$segmentLimit = 1;
//if($segmentCount > $segmentLimit)
// $segmentLimit = $segmentCount;
$outputArray = array();
$i = 0;
while($dataCount >= $segmentLimit) {
if( $segmentCount == $i)
$i = 0;
if(!array_key_exists($i, $outputArray))
$outputArray[$i] = array();
$outputArray[$i][] = array_splice($array,0,$segmentLimit)[0] ;
$dataCount = count($array);
$i++;
}
if($dataCount > 0) $outputArray[] = $array;
return $outputArray;
}