在PHP中转置(翻转)表示为2-D数组的矩阵

时间:2018-03-15 09:52:13

标签: php arrays algorithm matrix transpose

我有一个像这样的数组

<?php 
$data =  [[1,2,3,4],[2,3,1,3],[6,2,5,1]];
?>

我想安排我的数组

<?php 
$dataIwant = [[1,2,6],[2,3,2],[3,1,5],[4,3,1]];
?>

如何用这样的结果循环数组?我真的很困惑超过2周来解决这个问题。但是变量$ data是动态的,现在$ data计算了3条记录,但是它将有超过3条记录,并且每条记录上的值总是相同的4.该数组是矩阵2D的表示

就像这样,但这个脚本仅用于静态数组

<?php 
$data =  [[1,2,3,4],[2,3,1,3],[6,2,5,1]];
$dataIwant = [];
foreach($data[0] as $key =>$value){
   $dataIwant[] = array($data[0][$key],$data[1][$key],$data[2][$key]); 
}

1 个答案:

答案 0 :(得分:0)

以下是进行转置的代码段。

请参阅代码中的注释以获取解释。

$data =  [[1,2,3,4],[2,3,1,3],[6,2,5,1]];

// Get width and height of the original matrix
$n = count($data);
$m = $n > 0 ? count($data[0]) : 0;

// Initialize the result matrix.
// PHP will automatically "expand" the array when you set elements by indexes
$dataIwant = [];

// Iterate over all the cells,
// $i goes through the 1st dimension, $j through the 2nd dimension
for ($i = 0; $i < $n; ++$i) {
  for ($j = 0; $j < $m; ++$j) {
    // Copy the elements from the source matrix to the result matrix, 
    // WITH FLIPPED INDEXES.
    $dataIwant[$j][$i] = $data[$i][$j];
  }
}

print_r($dataIwant);