Jump to content

Regrouping arrays


silkfire

Recommended Posts

How do you solve this problem? I have a flat array that I need to transform into a 2D array where every fourth item is group together and contains 4 items.

 

From:

 

array(

          0,

          1,

          2,

          3,

          4,

          5,

          6,

          7,

          8,

          9,

          10,

          11,

          12,

          13,

          14,

          15

)

 

To:

 

array(

          array(0, 4, 8, 12),

          array(1, 5, 9, 13),

          array(2, 6, 10, 14),

          array(3, 7, 11, 15)

)

 

I'm sure there's some easy solution...

Note that I need to transform it, not create one from scratch.

Link to comment
https://forums.phpfreaks.com/topic/248879-regrouping-arrays/
Share on other sites

hmmm... array_chunk will allow you to split into groups of 4 elements, but will maintain the same order as the original array... You could then re-organize them with a simple for() loop using the keys 0,1,2 and 3.

 

How is the original array built? (what values will it contain? just a sequence of numbers like your example? or can it contain other values or non-sequential values?)

 

Link to comment
https://forums.phpfreaks.com/topic/248879-regrouping-arrays/#findComment-1278096
Share on other sites

c'mon, just try what I suggested first, and then worry about wrapping it into a function.

 

<?php
$initialArray = array(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15);
$chunks = array_chunk($initialArray, 4);
$final = array();
$key = 0;
foreach($chunks as $k=>$chunk){
for($i=0;$i<4;$i++){
	$final[$i][$key] = $chunk[$i];
}
$key++;
}
echo '<br>';
print_r($final);
?>

Link to comment
https://forums.phpfreaks.com/topic/248879-regrouping-arrays/#findComment-1278109
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.