我有两个饼干及其价值如下:
$url = "http://www.google.com"
PowerShell Invoke-WebRequest -Uri $url -Method GET
但它只打印一个值。如何添加这两个值来对它们求和?
答案 0 :(得分:3)
我认为你不需要array_sum,只需使用+ =运算符就可以节省一点内存
$t_cost = 0;
foreach($_COOKIE as $key=>$val) {
$piece = explode(",", $val);
$t_cost += $piece[3];
}
echo $t_cost;
答案 1 :(得分:2)
实际上不需要array_sum
。
// the array where all piece[3] values are stored
$t_cost = array();
// loop through array
// just foreach($_COOKIE as $val) is enough
foreach($_COOKIE as $key=>$val) {
// split by comma
$piece = explode(",", $val);
// add to array
$t_cost[] = $piece[3];
}
// sum up
$total_cost = array_sum($t_cost);
或只是
$total = 0;
foreach($_COOKIE as $key=>$val) {
$piece = explode(",", $val);
$total += $piece[3];
}
echo $total;
答案 2 :(得分:1)
$total = 0;
foreach($_COOKIE as $key=>$val) {
$piece = explode(",", $val);
$t_cost = trim(str_replace('$', '', array($piece[3]));
$total += (float)$t_cost;
echo "The total cost: $".$total;
}