如何爆炸一个字符串并计算总和?

时间:2019-05-05 02:24:35

标签: php arrays

我希望将$ total作为一个数字的总和输出,但是每次我总结$ total时,它都会输出多个数字

$total =0   // i tried to use a number to sum them up
$computers = array(
"computer;DT-12;568,36;10",
 "Samsung; RS; 562,26;11",
 "Hewlett Packard;  F12; 450,23; 23",
"Toshiba; LO-34; 454,23;8",
 "Sony; Vaio 123; 232,23;5"
);
foreach($computers   as $value)
{
$product= explode(";",$value);

    $price = $product[2];

         $count = $product[3];
           $multiply = $count * $price;
$total += $multiply

}

预期输出:

$total =  27004 as one number

1 个答案:

答案 0 :(得分:1)

您的代码中有一些语法错误。除此之外,您的计算看起来还不错,并且使用explode();做得很好。

代码:

$computers = array(
    "computer;DT-12;568,36;10",
    "Samsung; RS; 562,26;11",
    "Hewlett Packard;  F12; 450,23; 23",
    "Toshiba; LO-34; 454,23;8",
    "Sony; Vaio 123; 232,23;5",
);

$total = 0;
foreach ($computers as $value) {
    $product = explode(";", $value);
    $total += (int) trim($product[2]) * (int) trim($product[3]);
}

var_dump($total);

输出:

您可能会检查一下数学是否正确。

int(27004)