0

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.

1
  • 3
    Your second code block has no relation to the first. Can you give an example of input-output? Commented Mar 31, 2010 at 13:53

1 Answer 1

6

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;
}
Sign up to request clarification or add additional context in comments.

4 Comments

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 Now that's some micro optimization if I've ever seen some. :o)
@deceze: You were quicker than 5 mins, so it wouldn't let me haha
@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. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.