在php中总结两个数组的值

时间:2016-04-17 16:10:21

标签: php arrays

有一个问题:

提交表单后,我收到索引数组作为SQL查询结果,目标是将每个下一个数组值与先前接收到的数组的值相加,并将总和放入结果数组

示例:

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

怎么做?

创建数组的代码:

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

提交$ product_amount数组后获取新数据,此新值必须与之前的数字相加。

2 个答案:

答案 0 :(得分:0)

您可以通过合并array_maparray_sum来实现此目的。如果您使用的是PHP 5.6或更高版本,那么您可以编写如下内容:

$total = array_map(function (...$vals) {
    return array_sum($vals);
}, ...$results);

假设$results包含所有$product_amount数组。

如果您想逐步构建$total而不是一次传递所有查询结果,则可以执行以下操作:

// Initialize $total array
$total = [0, 0, 0];

// Update $total for each query
$total = array_map(function (...$vals) {
    return array_sum($vals);
}, $total, $product_amount);

答案 1 :(得分:0)

通过正确使用会话可以解决这个问题:

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

特别感谢Mawia HL的帮助。