Vettel Posted September 26, 2010 Share Posted September 26, 2010 I have an array with 192 items in it (0-191) and I want to rearrange them into a multidimensional array with 24 sets of 8. If I wasn't very clear there, here's an abbreviated version of what I want: $arr1 = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23); $arr2 = array(array(0, 1, 2, 3, 4, 5, 6, 7), array(8, 9, 10, 11, 12, 13, 14, 15), array(16, 17, 18, 19, 20, 21, 22, 23)); Thank you in advance! Quote Link to comment Share on other sites More sharing options...
jcbones Posted September 26, 2010 Share Posted September 26, 2010 <?php $arr1 = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23); $i = 0; $n = 0; foreach($arr1 as $v) { $arr2[$n][] = $v; $n = ($i < ? $n : ++$n; $i = ($i >7) ? 0 : ++$i; } echo '<pre>'; print_r($arr2); echo '</pre>'; ?> Quote Link to comment Share on other sites More sharing options...
Alex Posted September 26, 2010 Share Posted September 26, 2010 There's a built-in function for this: array_chunk. print_r(array_chunk($arr1, ); Quote Link to comment Share on other sites More sharing options...
jcbones Posted September 26, 2010 Share Posted September 26, 2010 I had a feeling that was the case. Quote Link to comment Share on other sites More sharing options...
Vettel Posted September 26, 2010 Author Share Posted September 26, 2010 Thank you jcbones- your solution almost work- it got the arrays right, but it jumbled up the values a bit. Thanks also Alex- I've never heard of array_chunk() before- very useful Much appreciated both of you Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.