在不改变列数的情况下翻转(转置)二维数组的行和列 [英] Flip (transpose) the rows and columns of a 2D array without changing the number of columns
问题描述
通常,我会问如何像这样转换一个 4 行、3 列的数组:
Normally, I'd be asking how to turn a 4-rowed, 3-columned array like this:
1 2 3
4 5 6
7 8 9
10 11 12
变成一个 3 行、4 列的数组,例如:(我不想要这个)
Into a 3-rowed, 4-columned array like: (I DON'T WANT THIS)
1 4 7 10
2 5 8 11
3 6 9 12
但实际上,我想把它变成这样:(我想要这个)
But actually, I want to turn it into this: (I WANT THIS)
1 5 9
2 6 10
3 7 11
4 8 12
换句话说,我想翻转行和列,但保持相同的宽度"和高度"的新阵列.我已经坚持了一个多小时.
In other words, I want to flip the rows and columns, but keep the same "width" and "height" of the new array. I've been stuck on this for over an hour.
这是我用来进行正常翻转"的函数(第一个例子):
This is the function I'm using to do a normal "flip" (the first example):
function flip($arr)
{
$out = array();
foreach ($arr as $key => $subarr)
{
foreach ($subarr as $subkey => $subvalue)
{
$out[$subkey][$key] = $subvalue;
}
}
return $out;
}
推荐答案
只需按照正确的顺序遍历数组即可.假设您有相对较小的阵列,最简单的解决方案就是在该过程中创建一个全新的阵列.
Just walk the array in the correct order. Assuming you have relatively small arrays, the easiest solution is just to create a brand new array during that walk.
解决方案将采用以下形式:
A solution will be of the form:
$rows = count($arr);
$ridx = 0;
$cidx = 0;
$out = array();
foreach($arr as $rowidx => $row){
foreach($row as $colidx => $val){
$out[$ridx][$cidx] = $val;
$ridx++;
if($ridx >= $rows){
$cidx++;
$ridx = 0;
}
}
}
这篇关于在不改变列数的情况下翻转(转置)二维数组的行和列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!