PHP从数据库求和值 - 多维数组

时间:2013-05-03 13:20:58

标签: php multidimensional-array foreach sum

我需要计算购物车中商品的子总数。它将添加到购物车的商品存储为会话变量中的产品ID数组。

首先,我需要使用购物车数组中的ID从数据库中提取产品信息(名称,价格等),然后添加购物车中所有商品的价格,其中可能有不止一个相同的产品。

我的测试车的总价格应为96,049.98,但我的代码总价格为18.我不知道从哪里获得。

以下是代码:

function subTotal() {
global $db;
global $table_prefix;
$table = $table_prefix . "products";

foreach($_SESSION['cart'] as $item) {
    $sql = $db->prepare("SELECT * FROM $table WHERE id = :id");
    $sql->bindParam(":id", $item[0]);
    $sql->execute();

    $amount = 0;
    $product = $sql->fetch(PDO::FETCH_ASSOC);
    foreach($product as $price) {
        $amount += $price['price'];
    }
}   
return $amount;
}

3 个答案:

答案 0 :(得分:2)

您正在每次迭代重新启动值$amount

尝试在顶部初始化它:

function subTotal() {
global $db;
global $table_prefix;
$table = $table_prefix . "products";
$amount = 0;  //MOVED HERE at the top

foreach($_SESSION['cart'] as $item) {
    $sql = $db->prepare("SELECT * FROM $table WHERE id = :id");
    $sql->bindParam(":id", $item[0]);
    $sql->execute();

    $product = $sql->fetch(PDO::FETCH_ASSOC);
    foreach($product as $price) {
        $amount += $price['price'];
    }
}   
return $amount;
}

答案 1 :(得分:1)

只需取出$amount = 0即可。因为它会在每个产品循环中重置。

$amount = 0;
foreach($_SESSION['cart'] as $item) {
    $sql = $db->prepare("SELECT * FROM $table WHERE id = :id");
    $sql->bindParam(":id", $item[0]);
    $sql->execute();    
    $product = $sql->fetch(PDO::FETCH_ASSOC);
    foreach($product as $price) {
        $amount += $price['price'];
    }
} 

答案 2 :(得分:1)

正如我在评论中提到的:如果您能够更改购物车存储商品的方式,您可以将代码重构为以下内容:

function subTotal() {
    $db = $GLOBALS['db'];
    $table_prefix = $GLOBALS['table_prefix'];

    $table = $table_prefix . "products";
    $totalPrice = 0;

    // assuming that you actually store ($id => $amount) pairs
    $ids = join(',', array_map('intval', array_keys($_SESSION['cart'])));

    $stmt = $db->prepare("SELECT id, price FROM $table WHERE id IN ($ids)");
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
       $amount = $_SESSION['cart'][$row['id']];
       $totalPrice += $amount * $row['price'];
    }

    return $totalPrice;
}

如果假设您的购物车变量包含以下内容:

array(
   4 => 1,   // 1 item with ID 4
   22 => 8   // 8 items with ID 22
)