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! Link to comment https://forums.phpfreaks.com/topic/214399-straight-forward-multidimensional-array-question/ 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>'; ?> Link to comment https://forums.phpfreaks.com/topic/214399-straight-forward-multidimensional-array-question/#findComment-1115687 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, ); Link to comment https://forums.phpfreaks.com/topic/214399-straight-forward-multidimensional-array-question/#findComment-1115697 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. Link to comment https://forums.phpfreaks.com/topic/214399-straight-forward-multidimensional-array-question/#findComment-1115699 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 Link to comment https://forums.phpfreaks.com/topic/214399-straight-forward-multidimensional-array-question/#findComment-1115706 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.