Udders
Udders

Reputation: 6976

Transpose a multidimensional array containing elements with inconsistent depths

I have array that looks like this,

    Array
(
    [email_address] => Array
        (
            [0] => sadasdasd
            [1] => Simosdsad
        )

    [firstname] => Array
        (
            [0] => sadsadas
            [1] => simon
        )

    [surname] => Array
        (
            [0] => asdasdasdasdasd
            [1] => ainley
        )

    [companies_company_id] => 
    [save_user] => Save User
)

all the keys [0] are related is there away to make these there own array?

Upvotes: 1

Views: 61

Answers (2)

mickmackusa
mickmackusa

Reputation: 47894

To transpose the columnar data of your input array, use a nested loop which is only entered if a subarray is encountered. The result array declarations will merely swap the first level keys with the second level keys -- this avoids the clunkiness of declaring individual array variables. Demo

$result = [];
foreach ($array as $k => $row) {
    if (is_array($row)) {
        foreach ($row as $i => $v) {
            $result[$i][$k] = $v;
        }    
    }
}
var_export($result);

Output:

array (
  0 => 
  array (
    'email_address' => 'sadasdasd',
    'firstname' => 'sadsadas',
    'surname' => 'asdasdasdasdasd',
  ),
  1 => 
  array (
    'email_address' => 'Simosdsad',
    'firstname' => 'simon',
    'surname' => 'ainley',
  ),
)

Upvotes: 0

Daniel Bingham
Daniel Bingham

Reputation: 12914

A simple way to do this would be something like this:

$newArray = array();
foreach($array as $key => $value)  {
    $newArray[] = $value[0];
}

Is there a reason you haven't?

Upvotes: 1

Related Questions