0

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'
]
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
  • `array_combine` is for creating an associative array from an array of keys and an array of values. What you want has nothing to do with that. – Barmar Oct 25 '22 at 21:06
  • This is basically just transposing the array, not merging anything. – Barmar Oct 25 '22 at 21:17
  • When performing this "transposition", are the first level keys actually important to preserve? – mickmackusa Oct 25 '22 at 21:27

2 Answers2

0

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

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.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136