First, what you don't want (which is half of the solution to what you do want)...
The term for "flipping rows and columns" is "transposing".
PHP has had a sleek native technique for this very action since the splat operator was added to the language.
The caveats to bear in mind are:
- All keys must be numeric. The splat/spread operator will choke on non-numeric keys.
- The matrix must be complete. If there are any gaps, you may not get the result that you desire.
Code: (Demo)
$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12],
];
var_export(
array_map(null, ...$matrix)
);
Output:
[
[1, 4, 7, 10],
[2, 5, 8, 11],
[3, 6, 9, 12],
];
Now, for what you do want!
Here is a functional-style snippet that incorporates php's transposing technique while ensuring that the output has the same number of columns as the input.
Code: (Demo)
var_export(
array_map(
null,
...array_chunk(
array_merge(...$matrix),
count($matrix)
)
)
);
Output:
[
[1, 5, 9],
[2, 6, 10],
[3, 7, 11],
[4, 8, 12],
];
This approach flattens the input, then breaks it into rows with lengths equivalent to the original number of rows, then that result is transposed.
Late Edit: As a purely academic pursuit, I wanted to see what a pure mathematical technique would look like which didn't use any conditions and didn't maintain multiple "counters".
As it turns out, because php arrays will truncate float keys to integers, this can be done in a single loop.
// assuming the earlier mentioned 3x4 matrix:
i old pos new pos i%rows i/rows i/col i%col
0 : [0][0] => [0][0] 0 0 0 0
1 : [1][0] => [0][1] 1 0.25 0.3 1
2 : [2][0] => [0][2] 2 0.5 0.6 2
3 : [3][0] => [1][0] 3 0.75 1 0
4 : [0][1] => [1][1] 0 1 1.3 1
5 : [1][1] => [1][2] 1 1.25 1.6 2
6 : [2][1] => [2][0] 2 1.5 2 0
7 : [3][1] => [2][1] 3 1.75 2.3 1
8 : [0][2] => [2][2] 0 2 2.6 2
9 : [1][2] => [3][0] 1 2.25 3 0
10 : [2][2] => [3][1] 2 2.5 3.3 1
11 : [3][2] => [3][2] 3 2.75 3.6 2
Code: (Demo)
$rows = count($matrix);
$cols = count(current($matrix));
$cells = $rows * $cols;
$result = $matrix; // used to preserve original key orders
for ($i = 0; $i < $cells; ++$i) {
$result[$i % $rows][$i / $rows] = $matrix[$i / $cols][$i % $cols];
}
var_export($result);
array_flip
? Won't this do? – Celanesearray_column()
function – Psychophysics