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条)

报告相同问题?

悬赏问题

  • ¥100 数字取证课程 关于FAT文件系统的操作
  • ¥15 如何使用js实现打印时每页设置统一的标题
  • ¥15 安装TIA PortalV15.1报错
  • ¥15 能把水桶搬到饮水机的机械设计
  • ¥15 Android Studio中如何把H5逻辑放在Assets 文件夹中以实现将h5代码打包为apk
  • ¥15 使用小程序wx.createWebAudioContext()开发节拍器
  • ¥15 关于#爬虫#的问题:请问HMDB代谢物爬虫的那个工具可以提供一下吗
  • ¥15 vue3+electron打包获取本地视频属性,文件夹里面有ffprobe.exe 文件还会报错这是什么原因呢?
  • ¥20 用51单片机控制急停。
  • ¥15 孟德尔随机化结果不一致