我在计算数组的总值时遇到困难。我不知道如何访问它。下面是我的代码:
if (file_exists('data.txt')) {
$result = file('data.txt');
foreach ($result as $value) {
$columns = explode('!', $value);
echo '<tr>
<td>' . $columns[0] . '</td>
<td>' . $columns[1] . '</td>
<td>' . $columns[2] . ' лв.</td>
<td>' . $type[trim($columns[3])] . '</td>
</tr>';
$cost = (float) $columns[2];
$totalCost = array($cost);
var_dump($totalCost);
}
}
?>
var_dump($cost) 结果:
float(2.5) float(35) float(2.5) float(20)
和 var_dump($totalCost):
array(1) { [0]=> float(2.5) }
array(1) { [0]=> float(35) }
array(1) { [0]=> float(2.5) }
array(1) { [0]=> float(20) }
我需要获取 $cost 内浮点数的总价值。
继续将成本添加到数组中并在循环迭代后计算总和:
$costs = array();
foreach ($result as $value) {
$columns= explode('!', $value);
echo '<tr>
<td>'.$columns[0].'</td>
<td>'.$columns[1].'</td>
<td>'.$columns[2].' лв.</td>
<td>'.$type[trim($columns[3])].'</td>
</tr>';
$costs[] = (float) $columns[2];
}
$totalCost = array_sum($costs);
您的代码应该是
<?php
if(file_exists('data.txt')){
$result= file('data.txt');
foreach ($result as $value) {
$columns= explode('!', $value);
echo '<tr>
<td>'.$columns[0].'</td>
<td>'.$columns[1].'</td>
<td>'.$columns[2].' лв.</td>
<td>'.$type[trim($columns[3])].'</td>
</tr>';
$totalCost +=(float)$columns[2];
}
echo $totalCost; // This will give you total value
}
?>