A
A
Andrey Filippov2015-09-25 15:05:08
PHP
Andrey Filippov, 2015-09-25 15:05:08

How to merge arrays by key?

I have a two dimensional array:

$users = [
    'name' => ['John', 'George', 'Tom'],
    'age' => [32, 25, 44],
];

You need to get an array like this:
$users = [
    ['name' => 'John', 'age' => 32],
    ['name' => 'George',  'age' => 25],
    ['name' => 'Tom', 'age' => 44],
];

So far the only code that comes to mind is:
$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;
}

Thanks

Answer the question

In order to leave comments, you need to log in

3 answer(s)
C
Curly Brace, 2015-09-25
@stasuss

php.net/manual/en/ref.array.php

T
tigra, 2015-09-25
@tigroid3

I already asked a similar question
HERE

D
Denis, 2015-09-25
@prototype_denis

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 question

Ask a Question

731 491 924 answers to any question