1

I have an array in the following form,

Array
(
    [foo] => Array
        (
            [3] => hello
            [1] => world
        )
    [bar] => Array
        (
            [3] => Some other stuff
            [1] => Some more stuff 
        )
    [baz] => Array
        (
            [3] => value
        )
)

How could I have it on the following form:

Array
(
    [3] => Array
        (    
            [foo] => hello
            [bar] => Some other stuff           
            [baz] => value
        )
    [1] => Array
        (
            [foo] => world
            [bar] => Some more stuff  
        )
)

Thanks

5
  • 3
    Have you tried doing this and not succeeded ? Commented Apr 11, 2011 at 16:35
  • 1
    In the second code block: what is the significance of [bar][1] => Some more stuff? Commented Apr 11, 2011 at 16:35
  • [bar][1] is really not making sense here. In fact, none of these keys are making sense. Please clarify. Commented Apr 11, 2011 at 16:37
  • You could accomplish it in about three lines of code, with two nested foreach loops. Did you try this yourself before asking us to do it for you? Commented Apr 11, 2011 at 16:37
  • @Josh Darrow: Don't forget to accept the correct answer. Just tick the check mark next to it. If you don't get in the habit now you will be doomed on this site. Commented Apr 11, 2011 at 16:49

1 Answer 1

3
$array;  //<--- assuming this is the array you are starting with

$new_array = array();  //<--- This is the new array you're building

foreach($array as $i=>$element)
{
    foreach($element as $j=>$sub_element)
    {
        $new_array[$j][$i] = $sub_element; //We are basically inverting the indexes
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.