Search code examples
phparraysmultidimensional-arraysummultiplication

Summing then multiplying rows and columnar values in a 2d array


I have a 2 dimensional array like this

array(
    array(
        'column1' => 10,
        'column2' => 11
    ),
    array(
        'column1' => 25,
        'column2' => 137
    ),
    array(
        'column1' => 21,
        'column2' => 58
    )
)

The keys column1 and column2 are fixed. They do not change.

I need to perform various functions on the data in this 2D array. The various functions can be grouped in two ways:

  • Row-wise first
  • Column-wise first

An example for Row-wise first functions,

I want to sum up all the numbers row-wise first before multiplying by columns.

So the expected behavior is (10+11) * (25+137) * (21+58)

An example for Column-wise first functions,

I want to sum up all the numbers column-wise first before multiplying by rows.

So the expected behavior is (10+25+21)*(11+137+58)

I have no problems writing out my own component functions. In the above, I need only two component functions sum and product

function sum (adden1, adden2) {
    return adden1 + adden2;
}

function product (multiplicant1, multiplicant2) {
    return multiplicant1 * multiplicant2;
}

The problem is the mapping. I want to reduce the number of for-loops I need to write. I want my code to be more modular because there are situations where the required behaviors are like:

  1. Perform this for each row 100-(column1+column2) / column2 and then sum up all the results.

There are too many formulae I need to work. But I am very confident that basically it is all a mixture of either performing row-wise first or column-wise first.

Hope to get some suggestions on the mapping of the values to the functions.

UPDATE:

Eventually I redesign my architecture to make this issue go away. So this question no longer is applicable to me.


Solution

  • Row wise is the easiest to map:

    $a = array(
        array(
            'column1' => 10,
            'column2' => 11
        ),
        array(
            'column1' => 25,
            'column2' => 137
        ),
        array(
            'column1' => 21,
            'column2' => 58
        )
    );
    
    echo array_product(array_map('array_sum', $a)), "\n";
    

    Column wise needs a utility function to grab all columns together into one array:

    echo array_product(array(
      array_sum(array_column($a, 'column1')),
      array_sum(array_column($a, 'column2'))
    )), PHP_EOL;
    
    function array_column(array $a, $column)
    {
      return array_map(function($item) use ($column) {
        return $item[$column];
      }, $a);
    }