gpt4 book ai didi

php - array_sum 以字符串形式返回值的总和

转载 作者:行者123 更新时间:2023-11-29 21:14:33 26 4
gpt4 key购买 nike

这看起来应该非常简单,但我不断得到意想不到的输出。我正在尝试访问 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 检索到的值的总和。这是怎么回事?

最佳答案

$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);

关于php - array_sum 以字符串形式返回值的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36070604/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com