如何在 php 的多维数组中求和

how to sum in a multidimensional array in php

例如,我有一个这样的数组:

$Batches = array(
    $Batch_1= array(
        $A_Row= array(1,1,0,0),
        $B_Row = array(0,0,0,1),
        $C_Row = array(0,0,0,1)),
    $Batch_2= array(
        $A_Row= array(1,0,0,0),
        $B_Row = array(0,0,0,1),
        $C_Row = array(0,0,0,1))
);

我想对每个 $n_Row:

求和

所以我应该得到这样的结果:

$Sum_Array = array(
     $A_row=array(2,1,0,0),
     $B_row= array(0,0,0,2),
     $C_row = array(0,0,0,2)
);

但我在尝试获得此结果时遇到困难,需要其他人提供一些 tips/advice。 到目前为止,这是我的代码:

//count rows and columns
$count_array= count($Batches);
$count_row = count($Batches[0]);
$count_column = count($Batches[0][0]);

$Array_sum = array();
for($array=0;$array<$count_array;$array++){
    for($row=0;$row<$count_row;$row++){
        for($col=0;$col<$count_column;$col++){
            //echo $Batches[$array][$row][$col] . "\n";
            if($Batches[$array][$row][$col]==1){
                $Batches[$array][$row][$col]++;
            }
            $Array_sum[]=$Batches[$array][$row][$col];
        }
    }
}

谁能在正确的方向上帮助我? 提前致谢。

我认为你的“阵列”

$Batches = array(
    $Batch_1= array(
        $A_Row= array(1,1,0,0),
        $B_Row = array(0,0,0,1),
        $C_Row = array(0,0,0,1)),
    $Batch_2= array(
        $A_Row= array(1,0,0,0),
        $B_Row = array(0,0,0,1),
        $C_Row = array(0,0,0,1))
);

是想象力的产物。但它也是有效的 PHP 代码。我假设您想使用键并且数组如下所示:

$Batches = array(
    'Batch_1' => array(
        'A_Row' => array(1,1,0,0),
        'B_Row' => array(0,0,0,1),
        'C_Row' => array(0,0,0,1)),
    'Batch_2' => array(
        'A_Row' => array(1,0,0,0),
        'B_Row' => array(0,0,0,1),
        'C_Row' => array(0,0,0,1))
);

求和与 foreach 配合使用效果更好。

$sum_arr = [];
foreach($Batches as $ib => $batch){
  foreach($batch as $ir => $row){
    foreach($row as $ic => $col){
      $sum_arr[$ir][$ic] ??= 0;
      $sum_arr[$ir][$ic] += $col;   
    }
  }
}

var_export($sum_arr);

输出:

array (
  'A_Row' => 
  array (
    0 => 2,
    1 => 1,
    2 => 0,
    3 => 0,
  ),
  'B_Row' => 
  array (
    0 => 0,
    1 => 0,
    2 => 0,
    3 => 2,
  ),
  'C_Row' => 
  array (
    0 => 0,
    1 => 0,
    2 => 0,
    3 => 2,
  ),
) 

求和也适用于原始数组。但是,这个数组只有数字键。