duanlu1922 2016-05-02 08:35
浏览 55
已采纳

找到数组-PHP的分数正数和负数

I have an array.Its have positive, negative and zero value.Now i want to count those number of positive, negative and zero value then divided each group by number of array count.I have tried below way:

<?php

$arr = ['-4','3','-9','0','4','1'];
$countNum = count($arr);
//print_r($countNum);
foreach ($arr as $key => $value) {
    if ($value<0) {
        continue;
    }elseif($value==0){
        continue;
    }else{
        $result = $value/$countNum;
        echo $result."</br>";
    }
}
?>

Output is :

0.5
0.66666666666667
0.16666666666667

But i want and should be:

for positive, 3/6=0.500000
for negative, 2/6=0.333333
for zero, 1/6=0.166667
  • 写回答

6条回答 默认 最新

  • douyi6818 2016-05-02 08:41
    关注

    Try this code.

    <?php
    $zero = '0';
    $positive = '0';
    $negative = '0';
    $arr = array('-4','3','-9','0','4','1');
    $total = count($arr);
    foreach ($arr as $num){
        if ($num > '0'){
        $positive++;
        } else if ($num < '0'){
        $negative++;
        } else {
            $zero++;
        }
    }
    echo "Positive: ".$positive/$total;
    echo '<br />';
    echo "Negative: ".$negative/$total;
    echo '<br />';
    echo "Zero: ".$zero/$total;
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥30 求给定范围的全体素数p的(p-2)的连乘积
  • ¥15 VFP如何使用阿里TTS实现文字转语音?
  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页