【问题标题】:array_sum returning the sum of values as stringarray_sum 以字符串形式返回值的总和
【发布时间】:2016-03-17 20:02:39
【问题描述】:

这看起来应该很简单,但我不断得到意想不到的输出。我正在尝试访问 SQL 数据库中的指定行,每个行都包含一个数值,然后计算这些值的总和。即使在我将值的数据类型设置为浮点数之后,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 中检索到的。 这是怎么回事?

【问题讨论】:

  • 您好,我的用户名是'; drop table populations; --
  • 是的,我还需要实现mysqli_real_escape_string

标签: php mysql sql arrays foreach


【解决方案1】:
$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);

【讨论】:

  • 太棒了。感谢您的帮助
【解决方案2】:

首先,不要用空字符串初始化数组。改为这样做:

$total = array();

或使用新样式:

$total = [ ];

其次,像这样重写 floatval 的东西:

array_push($total, floatval($value));

这应该可以解决它...

【讨论】:

  • 我刚刚实施了你的建议——很遗憾,输出没有变化。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-10
  • 2016-10-19
  • 1970-01-01
  • 2022-01-03
相关资源
最近更新 更多