...

View Full Version : Split indexed single dimension array into groups of X (2 dimension array)



MattyUK
02-11-2010, 04:30 AM
If I have a single dimensioned indexed array that I want split into groups what is the best way to do this?

If I have this:


Array
(
[0] => Value0
[1] => value1
[2] => value2
[3] => value3
[4] => value4
[5] => value5
[6] => value6
[7] => value7
[8] => value8
[9] => value9
[10] => value10
[11] => value11
[12] => value12
[13] => value13
[14] => value14
[15] => value15
[16] => value16
[17] => value17
[18] => value18
[19] => value19
[20] => value20
[21] => value21
[22] => value22
[23] => value23
[24] => value24
[25] => value25
[26] => value26
)


but I need this:


Array
(
[0] => Array
(
[0] => Value0
[1] => value1
[2] => value2
[3] => value3
[4] => value4
[5] => value5
[6] => value6
[7] => value7
[8] => value8
)

[1] => Array
(
[0] => value9
[1] => value10
[2] => value11
[3] => value12
[4] => value13
[5] => value14
[6] => value15
[7] => value16
[8] => value17
)

[2] => Array
(
[0] => value18
[1] => value19
[2] => value20
[3] => value21
[4] => value22
[5] => value23
[6] => value24
[7] => value25
[8] => value26
)
)


What is the most efficient way forward. I'm using using PHP 5.2

Thanks.

JAY6390
02-11-2010, 04:34 AM
array_chunk() (http://www.php.net/array_chunk)

$output_array = array_chunk($input_array, 9);
echo '<pre>'.print_r($output_array, true).'</pre>';

MattyUK
02-11-2010, 05:01 AM
OO thanks. I hadn't stumbled across array_chunk before.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum