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'
]
2
Answers
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.
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.
If you need to preserve those first level keys, you can re-apply them after tranposing.
Code: (Demo)
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)
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.