1

My form produces a 3 dimensional array. I would like to transform this array into a 2 dimensional one.

I tried this with no success:

$_rows = array();
foreach ($_contacts as $name => $_arr) {
   foreach ($_arr as $key => $val) {
        $_rows[] = array ($name => $val);
   }
}

Data Source:

[_contacts] => Array
    (

    [name] => Array
            (
                [0] => foo
                [1] => bar
            )

    [phone] => Array
            (
                [0] => 012345
                [1] => 098765
            )

    [email] => Array
            (
                [0] => mail.com
                [1] => yahoo.com
            )
    )

Desired output:

 Array
    (
        [0] => Array
            (
                [name] => foo
                [phone] => 012345
                [email] => mail.com
            )

        [1] => Array
            (
                [name] => bar
                [phone] => 098765
                [email] => yahoo.com
            )
    )

Any thoughts were I went wrong?

1 Answer 1

2
$_rows = array();     
foreach ($_contacts as $name => $_arr) {          
   foreach ($_arr as $key => $val) {            
        $_rows[$key][$name] = $val;
   }
}
Sign up to request clarification or add additional context in comments.

3 Comments

One more thing please. As I can not create an array like this (empty)? array ( [name] => [phone] => [email]=> )? thanks
You can use something like array('name' => null, 'phone' => null, 'email' => null) or array('name' => '', 'phone' => '', 'email' => '')
I'd like to skip to create 2nd level array if the 3d level is empty. [_contacts] => Array ( [name] => Array ( [0] => foo [1] => ) [phone] => Array ( [0] => 012345 [1] => ) [email] => Array ( [0] => mail.com [1] => ) )

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.