这似乎应该非常简单,但我不断得到意想不到的输出。我正在尝试访问SQL数据库中的指定行,每个行包含一个数值,然后计算这些值的总和。即使在我将值的数据类型设置为float之后,PHP也会将这些值连接起来,就好像它们是字符串一样。我的代码:
$query = "SELECT * FROM populations WHERE username ='{$_SESSION[name]}' AND region_name = 'region'"
$query .= "AND city_name = 'city'";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)) {
$population_value = $row['population_value'];
$population_value = is_array($population_value) ? $population_value : array($population_value);
foreach($population_value as $value){
echo $value;
}
echo array_sum($population_value);
}
我也尝试过:
$total = array("");
foreach($population_value as $value){
floatval($value);
array_push($total, $value);
echo $value;
}
echo array_sum($total);
我的输出总是如下:100002000030000 10,000 20,000和30,000是每个人口的价值。
我已成功使用foreach
计算了使用未从MySQL检索到的值的总和。
这是怎么回事?
答案 0 :(得分:0)
首先,不要使用空字符串初始化数组。这样做:
$total = array();
或使用新风格:
$total = [ ];
其次,重写 floatval 这样的事情:
array_push($total, floatval($value));
那应该解决它......
答案 1 :(得分:0)
$query = "SELECT * FROM populations WHERE username ='{$_SESSION[name]}' AND region_name = 'region'"
$query .= "AND city_name = 'city'";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)) {
$population_value = $row['population_value'];
//This is actually rewriting the array or NOT adding the value to it.
$population_value = is_array($population_value) ? $population_value : array($population_value);
//ok, so you're going to repeatedly output this?
foreach($population_value as $value){
echo $value;
}
echo array_sum($population_value);
}
我认为你想要的是:
$query = "SELECT * FROM populations WHERE username ='{$_SESSION[name]}' AND region_name = 'region'"
$query .= "AND city_name = 'city'";
$result = mysqli_query($connection, $query);
$population_value=array(); //Initialize the array so we can just add to it.
while($row = mysqli_fetch_assoc($result)) {
$population_value[]= intval($row['population_value']); //Just making sure we get a number.
echo end($population_value); //We could output the row again, or just grab the last element of the array we added.
}
//Now that the array is fully populated and we've made sure it's only numbers, we output the grand total.
echo array_sum($population_value);