Simon Haesaerts
Simon Haesaerts

Reputation: 53

Flatten an associative 3d array into an associative 2d array and sum column values

As an example I have an array like this:

$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)
    )
);

I want to sum per each $n_Row:

So I should get a result like this:

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

But I'm having difficulty trying to get this result and need some tips/advice from someone else. This is my code so far:

//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];
        }
    }
}

Anyone who can help me in the right direction? Thanks in advance.

Upvotes: 0

Views: 59

Answers (1)

jspit
jspit

Reputation: 7683

I think your "array"

$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))
);

is a product of the imagination. But it is also valid PHP code. I assume you want to work with keys and the array looks like this:

$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))
);

The Summation works better with 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);

The Output:

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,
  ),
) 

The summation also works with the original array. However, this array has only numeric keys.

Upvotes: 1

Related Questions