关于购物车中数组项目的 Woocommerce 问题

Woocommerce problem about array items in cart

这是我在购物车中的代码:

<?php 
$totaleiva_1 = 0;
$items = $woocommerce->cart->get_cart();
foreach($items as $item ) {
    echo $totaleforsebene;
    $totaleiva_1 = $totaleiva_1 + $totaleforsebene;
}
echo $totaleiva_1;
?>

结果是:我有的商品购物车最后一个商品的$totaleforsebene值加了n次(比如我有两个商品,最后一个值$totaleforsebene加了两次).

相反,我想要 $totaleforsebene 用于不同的产品,然后添加它们。

感谢帮助

您可以为每个产品创建包含 ID 的数组,然后添加正确的值:

当您计算 $totaleforsebene 时,请执行以下操作:

foreach($items as $item => $values) {
    $product = wc_get_product( $values['data']->get_id());
    ...
    $totaleforsebene = ($scontato * $percent)/100; 
    $totalForSebeneArray[$values['data']->get_id()] = $totaleforsebene; // add the value by the item ID
    $totaleforsebene = number_format($totaleforsebene, 2, '.', '')." €"; 
}

现在,当您在项目上循环并求和时,您可以这样做:

$totaleiva_1 = 0;
$items = $woocommerce->cart->get_cart();
foreach($items as $item ) {
    $totaleiva_1 += $totalForSebeneArray[$item ['data']->get_id()];
}
echo $totaleiva_1;

您还需要更好地格式化您的问题,因为现在很难理解您的问题,我什至不确定我的解释是否能回答您的问题...