Answer the question
In order to leave comments, you need to log in
How to merge arrays by key?
I have a two dimensional array:
$users = [
'name' => ['John', 'George', 'Tom'],
'age' => [32, 25, 44],
];
$users = [
['name' => 'John', 'age' => 32],
['name' => 'George', 'age' => 25],
['name' => 'Tom', 'age' => 44],
];
$keys = array_keys($users);
$result = [];
$size = count($users['name']);
for ($i=0; $i < $size; $i++) {
$row= [];
foreach ($keys as $key) {
$row[$key] = $users[$key][$i];
}
$result[] = $row;
}
Answer the question
In order to leave comments, you need to log in
Your array is an MxN matrix and you just need to rotate it 90 degrees.
To save the keys, we go not for, but foreach.
In the end it will turn out like this.
$output = [];
foreach ($users as $y => $values) {
foreach ($values as $x => $value) {
$output[$x][$y] = $value;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question