Php - display values ​​in a two-dimensional array and perform functions by values

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 column1and are column2fixed. They do not change.

I need to perform various functions on the data in this two-dimensional array. Various functions can be grouped in two ways:

  • First first
  • Column first

An example for the first Row-wise functions,

I want to sum all numbers row by row first before multiplying by columns.

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

An example for the first functions of a column,

I want to first sum all the numbers by columns before multiplying them by rows.

Thus, the expected behavior (10 + 25 + 21) * (11 + 137 + 58)

. , sum product

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

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

. for-loops, . , , , :

  • 100- (column1 + column2)/column2, .

, . , , .

.

UPDATE:

, . .

+5
2

:

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

wise :

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);
}
+1

- . array_map _walk.

:

<?php
$input = array(
    array(
        'column1' => 10,
        'column2' => 11
    ),
    array(
        'column1' => 25,
        'column2' => 137
    ),
    array(
        'column1' => 21,
        'column2' => 58
    )
);

echo 'Row wise : ', array_product(array_map(
    function($row){ 
     return $row['column1'] + $row['column2']; 
    }, $input)), '<br/>';

$output = array(0,0);
array_walk($input, 
  function($val, $key, &$output){ 
     $output[0] += $val['column1'];
     $output[1] += $val['column2'];
  }, &$output);
echo 'Column wise : ', array_product($output);


?>
+1

All Articles