gpt4 book ai didi

php - 与 PHP 数组相比,使用 MySQL 查询数组时获得不同的结果

转载 作者:行者123 更新时间:2023-11-29 14:19:53 25 4
gpt4 key购买 nike

我正在编写一个脚本来计算一组数据的众数、中位数和平均值。我有 10 条记录,它们存储在 MySQL 数据库和 PHP 数组中。当脚本完成时,脚本将只使用数据库中存储的数据,而不使用 PHP 数组,PHP 数组是用来测试代码的。

但我发现使用 PHP 数组与 MySQL 数组时的结果是不同的。在 PHP 数组中,我有以下数据:

$arr = array(60, 70, 71, 76, 144, 151, 197, 229, 233, 233);

在我的 MySQL 数据库中,我有以下代码:

$data = mysql_query("SELECT amount FROM example") or die(mysql_error()); 
$arr = mysql_fetch_array($data);

数据是相同的,异常(exception)的是 MySQL 数据在每条记录后包含 .00。在尝试找出为什么给出错误结果的过程中,我从数据库中的每条记录中删除了 .00。但数据仍然是错误的。

使用 PHP 数组时的结果给出了以下(正确的)结果:

Average (mean) value of payments £146.4
Payments values that occur most often £233
Median value of payments £151

使用 MySQL 数组时的结果给出了以下(错误)结果:

Average (mean) value of payments £144
Payments values that occur most often £144
Median value of payments £144

我无法解释为什么会发生这种情况。下面是我用来生成这些结果的 PHP 代码:

    <?php
function arithmetic($array, $output = 'mean'){
switch($output){
// This case works out the mean
case 'mean':
$count = count($array);
$sum = array_sum($array);
$total = $sum / $count;
break;
// This case works out the median
case 'median':
rsort($array);
$middle = round(count($array) / 2);
$total = $array[$middle-1];
break;
// This case works out the mode
case 'mode':
$v = array_count_values($array);
arsort($v);
foreach($v as $k => $v){$total = $k; break;}
break;
}
return $total;
}

// PHP Array with data
//$arr = array(60, 70, 71, 76, 144, 151, 197, 229, 233, 233);

// MySQL Connection & Retrieval of data
$data = mysql_query("SELECT amount FROM example") or die(mysql_error());
$arr = mysql_fetch_array($data);

?>

大家有什么想法吗?

更新:
我一直在玩MySQL查询,并使用以下代码:

$data = mysql_query("SELECT * FROM example") or die(mysql_error()); 
$arr = mysql_fetch_assoc($data);
print_r ($arr);

它仅显示以下结果:

Array ( [id] => 1 [amount] => 144 )

实际上,查询带来了所有记录,而不仅仅是一条记录。

最佳答案

嗯,原因是因为您只获取一行,因此只有一个数字......

$arr = array();

while ($result_array = mysql_fetch_row($data)) {
$arr[] = $result_array[0];
}

执行此代码后,您应该能够计算出正确的值。

关于php - 与 PHP 数组相比,使用 MySQL 查询数组时获得不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11921848/

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