简体   繁体   English

如何乘以多维数组中的行和列?

[英]How to multiply rows and columns in multidimensional array?

I need to multiply numbers in rows and in columns using nested for loops. 我需要使用嵌套的for循环将行和列中的数字相乘。

I have a sum of column, and I'm trying to use the same logic for multiplying rows but without any success... 我有一个列的总和,我试图使用相同的逻辑乘行,但没有成功...

$nxmArr = array(array());

$rows = 4;
$cols = 4;

$m = 0;

$colSum = 0;
$rowSum = 0;

for($i = 0; $i < $rows; $i++) {
  $colSum = 1;
  for($j = 0; $j < $cols; $j++) {
    $m++;
    $colSum *= $m;
    echo "$m ";
  }
  echo "Column Sum: $colSum<br>";
}

I have a list of numbers from 1 to 16, and I'm getting right results for every column, but when I try with rows I'm not getting right results... 我有一个从1到16的数字列表,每列我都得到正确的结果,但是当我尝试行时却没有得到正确的结果...

The difficulty is that you are not adding up values from the matrix, you are just calculating the value in each column as you go along (the value $m ). 困难在于您没有从矩阵中求出值,而只是在计算每一列中的值(值$m )。

This sets the values in the first set of loops and sets the values, then does the calculations using these values 这将在第一组循环中设置值并设置值,然后使用这些值进行计算

$rows = 4;
$cols = 4;
$nxmArr = [];
$value = 1;
for ( $row = 0; $row < $rows; $row++ )  {
    for ( $col = 0; $col < $cols; $col++ )  {
        $nxmArr[$row][$col] = $value++;
    }
}

// Start with rows...
for ( $row = 0; $row < $rows; $row++ )  {
    $rowSum = 1;
    // For each column
    for ( $col = 0; $col < $cols; $col++ )  {
        echo $nxmArr[$row][$col]." ";
        $rowSum *= $nxmArr[$row][$col];
    }
    echo " sum-".$rowSum.PHP_EOL;
}
/* Generates
1 2 3 4  sum-24
5 6 7 8  sum-1680
9 10 11 12  sum-11880
13 14 15 16  sum-43680
*/
// Then columns
for ( $col = 0; $col < $cols; $col++ )  {
    $colSum = 1;
    for ( $row = 0; $row < $rows; $row++ )  {
        echo $nxmArr[$row][$col]." ";
        $colSum *= $nxmArr[$row][$col];
    }
    echo " sum-".$colSum.PHP_EOL;
}
/* Generates
1 5 9 13  sum-585
2 6 10 14  sum-1680
3 7 11 15  sum-3465
4 8 12 16  sum-6144
 */

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM