dongtuan1980 2019-06-24 04:40
浏览 142
已采纳

PHP返回除零

I've a function in php, this is the function

public function actionGetTotal($id){
    $month = date('m');
    $year = date('Y');
    $arrayDataMitra = Yii::$app->db->CreateCommand("SELECT nilai FROM data WHERE MONTH(first_date) = '$month' AND YEAR(first_date) = '$year' AND idMitra = '$id' AND idProgram BETWEEN '7' AND '11'")->queryAll();
    $arrayNilai = array_column($arrayDataMitra, 'nilai');

    $countArr = count($arrayNilai);        
    $totalPoin = 0;
    for($i = 0; $i < $countArr; $i++){
        $totalPoin = $totalPoin + $arrayNilai[$i];                            
    }

    $totalPoin = $totalPoin / $countArr; //issue
    return $totalPoin;
}

if I printout as echo $totalPoin . ', ' . $countArr; die(); it will show 4, 2. But if I delete it, the function return Division by zero. It said the $countArr is 0. Anyone can explain why it happen?

Thanks

Update

If I do

$countArr = count($arrayNilai);        
echo '<pre>';
echo 'This is data array';
echo '<br>';
print_r($arrayNilai);
echo '<br>';
echo 'This is array count';
echo '<br>';
echo $countArr;
die();

it return

This is data array
Array
(
    [0] => 2
    [1] => 2
)

This is array count
2

UPDATE I think it's not the function logic error. I'm using Yii2 framework, and that function called inside the gridview in index.php. The cause is I've 3 rows of data where only a row that contain data. That's why the $countArr is 0, because in second row there is no data from the $arrayNilai. Thankyou

  • 写回答

2条回答 默认 最新

  • drtkyykai004574380 2019-06-24 05:01
    关注

    Well if the query return no data. It leads to division by zero. What would you expect the result to be in such case? Maybe zero? You have to handle this situation explicitly. Like

    if ($countArr===0) return 0;
    

    Or dont call the entire function at all, if there is no data.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog