我有一个未定义变量的问题,如果我定义变量脚本无法正常工作,我知道这是一个简单的答案,我找不到它。
这是我的代码:(我在每个循环中使用它)
$weight= ($item['weight']*$item['quantity']);
$totalweight = ($totalweight + $weight)
echo $totalweight;
该脚本完美无缺,并且在第2行$ totalweight上获得了一个未定义的变量错误
我试图设置变量然后打破计算。
答案 0 :(得分:1)
您需要初始化循环的外部,以便在每次迭代时都不会覆盖它:
$totalweight = 0;
foreach ($items as $item) {
$weight= ($item['weight']*$item['quantity']);
$totalweight = ($totalweight + $weight)
}
echo $totalweight;
答案 1 :(得分:0)
你是如何设置变量的? PHP正在发出此通知,因为您要求它添加$totalWeight
和$weight
并且它不知道$totalWeight
是什么。
要删除此通知,您可以执行以下操作:
$totalWeight = 0;
$weight= ($item['weight']*$item['quantity']);
$totalweight = ($totalweight + $weight);
echo $totalweight;
虽然最好将线路更改为:
$totalweight = $weight;
(当然,除非这个代码在循环中运行等)。