Home > Software engineering >  Restructure 2d array so that column values become row values (transpose but preserve first level key
Restructure 2d array so that column values become row values (transpose but preserve first level key

Time:10-26

The situation is as follows. I have a parent array which looks like the following:

$parent = [
    1 => ['test1', 'test2'],
    2 => ['test1_1', 'test2_2'],
];

I would like to group the data by column.

Desired result:

[
    1 => ['test1', 'test1_1'],
    2 => ['test2', 'test2_2'],
]

1 parent array called parent contains 2 arrays inside. I want to combine these two so that they have the same values as stated above. So this would mean that the arrays should be combined based on index number.

Since I do not make use of string keys, how would I accomplish this? I believe that there is no build in function available for this situation.

I would imagine that I could start beginning to create a new array and use a for loop through the parent array.

I tried the array-combine function however, this is NOT displaying the results I want.

[
    1 => ['test1' => 'test1_1', 'test2' => 'test2_2'
]

CodePudding user response:

If you need to preserve those first level keys, you can re-apply them after tranposing.

Code: (Demo)

var_export(
    array_combine(array_keys($parent), array_map(null, ...$parent))
);

Otherwise, you can just transpose and accept the re-indexed first level keys. Honestly, I can't see any good reason to preserve the first level keys because by transposing, you remove the initial association between first level keys and the row values.

Code: (Demo)

var_export(
    array_map(null, ...$parent)
);

If these techniques do not suit your actual project data, then we will need a more realistic sample array to be provided in your question body.

CodePudding user response:

Loop over the keys of the top-level array. Then use the current index of the iteration to get the corresponding columns of the nested arrays.

$result = [];
foreach (array_keys($parent) as $i => $k) {
    $result[$k] = array_column($parent, $i);
}

DEMO

This assumes the number of rows is the same as the number of columns. It's not clear what you expect the result to be if that's not true.

  • Related