2

I usually use Eloquent so transposing the data is much easier. However i'm struggling to this in vanilla PHP.

I have tried array_map(null, ...$array) however get an error due to it not being an array.

I have got the following keyed array:

[ 'email' => [ "[email protected]", "[email protected]" ], 'lastName' => [ 'Pool', 'Ball' ], 'firstName' => [ 'William', 'Martyn' ], 'id' => [ 'j8zwyk', '1' ] ] 

I need to convert this to the following format:

[ 0 => [ 'email' => "[email protected]", 'lastName' => 'Pool', 'firstName' => 'William', 'id' => 'j8zwyk' ], 1 => [ 'email' => "[email protected]", 'lastName' => 'Ball', 'firstName' => 'Martyn', 'id' => '1' ] ] 
0

2 Answers 2

7

Create new array with length 2 and loop through origin array. In loop insert relevant item into new array.

So if your array has only 2 item per key use

$newArr = []; foreach($arr as $key=>$item){ $newArr[0][$key] = $item[0]; $newArr[1][$key] = $item[1]; } 

But if it has unknown item use

$newArr = []; foreach($arr as $key=>$item){ foreach($item as $key2=>$item2) $newArr[$key2][$key] = $item2; } 

Check result in demo

Sign up to request clarification or add additional context in comments.

4 Comments

Close, but that doesn't account for if I get more than 2 emails etc... this is basically a form submitting, so the amount of emails and names etc could be any.
Spot on, thanks. I did think of doing it like this but I figured there might be a better way.
Second example is the best way, better than my answer, because it doesn't assume all child arrays have the same count.
Thanks for your help, I will mark that one as the answer then for historical reference.
4
$newArray = []; foreach ($array as $key => $value) { for ($i = 0; $i < count($value); $i++) { $newArray[$i][$key] = $value[$i]; } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.