Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Restructure 2d array so that column values become row values (transpose but preserve first level keys)

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
    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'
]

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading