petres
petres

Reputation: 582

Is there a buildin/short PHP functions which reverses `array_column`?

I have for example three arrays in one array:

$foo = [ 
    "id"      => [1, 3, 8],
    "name"    => ['one', 'three', 'eight'],
    "isLarge" => [false, true, true]
];

I want simple combine these arrays as exactly the reverse operation to array_column, basically I want to obtain:

$bar = [[
   "id" => 1,
   "name" => "one",
   "isLarge" => false
], [
   "id" => 3,
   "name" => "three",
   "isLarge" => true
], [
   "id" => 8,
   "name" => "eight",
   "isLarge" => true
]];

Thanks in advance!

One solution would be:

$bar = [];
for ($i = 0; $i < count($foo['id']); $i++) 
    $bar[] = [
        "id"      => $foo["id"][$i],
        "name"    => $foo["name"][$i],
        "isLarge" => $foo["isLarge"][$i]
    ];

But this seems a bit cumbersome.

Upvotes: 2

Views: 725

Answers (1)

iainn
iainn

Reputation: 17434

You can avoid hardcoding the column names by looping over the first row of your array, and then using a combination of array_combine and array_column to transpose it:

$keys = array_keys($foo);

$bar = [];

foreach(array_keys($foo[$keys[0]]) as $columnNumber) {
  $bar[] = array_combine($keys, array_column($foo, $columnNumber));
}

This takes each vertical "slice" of your 2d array, and uses each one to create a row in the output.

See https://3v4l.org/nscrh for a demo

On the off-chance that your resulting array doesn't need the column names and all you need is a pure transposition, you can use a much quicker option:

$bar = array_map(null, ...array_values($foo));

Upvotes: 1

Related Questions