Hello, I have the following array:

Array(
   [0] => 0,0
   [1] => 0,1
   [2] => 0,2
   [3] => 0,3
   [4] => 1,0
   [5] => 1,1
   [6] => 1,2
   [7] => 2,0
   [8] => 2,1
   [9] => 2,2
   [10] => 2,3 
)

And I would like to split it into the following structure:

Array( 

[0] => Array (
        [0] => 0
        [1] => 1
        [2] => 2
        [3] => 3
    )
[1] => Array (
        [0] => 0
        [1] => 1
        [2] => 2
        [3] => 3
    )
[2] => Array (
        [0] => 0
        [1] => 1
        [2] => 2
        [3] => 3
    )
[3] => Array (
        [0] => 0
        [1] => 1
        [2] => 2
        [3] => 3 
)

i.e., in the "X,Y" value, X corresponds to the position of value "Y" in the new array. I can't seem to get my head around the logic, its my first using 'foreach' in such a way.

Any help would be greatly appreciated pointing me in the right direction.

link|flag
3  
Your second code block has no relation to the first. Can you give an example of input-output? – Coronatus Mar 31 at 13:53

1 Answer

up vote 6 down vote accepted

The input and output arrays in your example don't quite match up, but I'm guessing you're looking for this:

$array = array(…as above…);
$newArray = array();

foreach ($array as $value) {
    list($x, $y) = explode(',', $value);
    $newArray[$x][] = $y;
}
link|flag
That did the trick, I owe you a drink sir! – aboved Mar 31 at 13:59
@aboved …and an "accepted answer" checkmark. :) – deceze Mar 31 at 14:01
This could be made a little bit more memory efficient by passing the $value into to the loop as a reference to the actual array element: foreach($array as &$value) { //... } – Techpriester Mar 31 at 14:04
@Techpriester Now that's some micro optimization if I've ever seen some. :o) – deceze Mar 31 at 14:06
@deceze: You were quicker than 5 mins, so it wouldn't let me haha – aboved Mar 31 at 14:13
show 1 more comment

Your Answer

 
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.