Leo240 Leo240 - 6 months ago 43
PHP Question

Summing the values of two arrays in php

There is a problem:

After submitting a form I receive the indexed array as a SQL-query result and the goal is to sum each next array values with the values of previously received arrays and put the sums into result array

Example:

// 1st query result
$product_amount = [0 => 0.36,
1 => 0.14,
2 => 0.42]

// 2nd query result
$product_amount = [0 => 0.28,
1 => 0.12,
2 => 0.40]

// n-th query result
$product_amount = [0 => 0.16,
1 => 0.14,
2 => 0.42]
// the sum
$total = [0 => 0.80,
1 => 0.40,
2 => 1.24]


How to do it?

The code that creates an array:

function doseCount($num){
return ($num/100) * intval($_POST['portion']); //getting multiplier for productAmount() function
}

function productAmount(){
global $link; //connection to the MySQL server
if(isset($_POST['product'])){
$product_amount_query = 'SELECT va.vitamin_a, va.vitamin_b1, va.vitamin_b2, va.vitamin_b3, va.vitamin_b5,
va.vitamin_b6, va.vitamin_bc_b9, va.vitamin_b12, va.vitamin_c, va.vitamin_d, va.vitamin_e, va.biotin, va.vitamin_k,
va.flavonoids, va.lipoic_acid FROM products_list p, vitamins_amount va WHERE p.id = va.product_id AND p.name = ?';

$product_amount_stmt = mysqli_prepare($link, $product_amount_query);
mysqli_stmt_bind_param($product_amount_stmt, "s", $_POST['product']);
mysqli_stmt_execute($product_amount_stmt);

$result = mysqli_stmt_get_result($product_amount_stmt);

$product = mysqli_fetch_array($result, MYSQLI_NUM);

return $product_final_result = array_map('doseCount', $product);
mysqli_stmt_close($product_amount_stmt);
mysqli_close($link);
}
}

$product_amount = productAmount();


After submit $product_amount array gets new data and this new value must be summed with previous.

Answer

This problem can be solved with proper use of sessions:

if (empty($_SESSION['product_amount'])){
    $_SESSION['product_amount'] = $product_amount;
}else{
    foreach ($_SESSION['product_amount'] as $key => $value) {
        $_SESSION['product_amount'][$key] += $product_amount[$key];
    }
}

Special thanks to Mawia HL for his help.