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
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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.