我正面临一个小问题,但遗憾的是无法修复它。寻求您的专家建议。
$rank = 13; //Sometimes empty or Null
$hits = 3; //Sometimes empty or Null
$rating = $rank/$hits;
if(is_nan($rating)){
$ratings = 0;
}
if(is_numeric($rating) ){
$ratings = number_format((float)$rating, 2, '.', '');
}else{
$ratings = 0;
}
$res['rating'] = $ratings;
如果 $ rank 或 $ hits 为空,我会将NaN作为输出。请告诉我我做错了什么。
答案 0 :(得分:3)
因为你必须检查$ hits的数量不要除以零。
<?php
$rank = 13; //Sometimes empty or Null
$hits = 3; //Sometimes empty or Null
function isOkRankandHits($hank, $hits){
if(isset($hank) && isset($hits)) //Check if hank or hits are not null
return is_numeric($hits) && is_numeric($hank) && $hits > 0; //OK, you can make the division.
//You don't specify if hank could have negative values
return false;
}
$ratings = 0; //for security and maintenance, always work with a default value
if(isOkRankandHits($rank, $hits)){ // ratings will be numeric
$ratings = $rank / $hits;
$ratings = number_format((float)$ratings, 2, '.', '');
}
$res['rating'] = $ratings;
?>
答案 1 :(得分:-1)
<?php
$rank = NULL; //Sometimes empty or Null
$hits = NULL; //Sometimes empty or Null
if(empty($rank))$rank =0;
if(empty($hits)){
$ratings =0;
} else {
$rating = $rank/$hits;
$ratings = number_format((float)$rating, 2, '.', '');
}
echo $ratings;
?>