views:

49

answers:

1

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.

+6  A: 

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;
}
deceze
That did the trick, I owe you a drink sir!
aboved
@aboved …and an "accepted answer" checkmark. :)
deceze
Techpriester
@Techpriester Now that's some micro optimization if I've ever seen some. :o)
deceze
@deceze: You were quicker than 5 mins, so it wouldn't let me haha
aboved
@deceze: Sure, it's not much, but i do this in EVERY foreach loop that allows it. After a while, it becomes quite a useful a habit and you don't forget it when you really need it. :)
Techpriester