从另一个获取一个PHP变量的百分比

时间:2012-09-23 21:14:24

标签: php

我试图从另一个获取一个php变量的百分比,例如我有两个信息数据库,第一个数据库充满了未识别的信息。第二个数据库充满了我们确定的信息。所以我想动态计算出所识别的总信息的百分比。

下面是一个用于计算百分比的php函数,

//TOTAL ENTRIES INTO Table 1 FOR total data
$result   = mysql_query( "SELECT * FROM table1" );
$num_total = mysql_num_rows( $result );

 //TOTAL ENTRIES IN Table 2  FOR THE PERCENTAGE
$result   = mysql_query( "SELECT * FROM table2" );
$num_amount = mysql_num_rows( $result );

 function percent($num_amount, $num_total) {
 $count1 = $num_amount / $num_total;
 $count2 = $count1 * 100;
 $count3 = 100 - $count2;
 $count = number_format($count3, 0);
 echo $count;
 }

两个查询都返回数据库中计算的总行数的正确信息,但count变量不返回任何信息。

任何想法或建议都将受到赞赏。

由于

斯坦

3 个答案:

答案 0 :(得分:6)

您回显结果,但不从函数返回。这可能就是问题所在。

但是,您可以在SQL中进行所有百分比计算:

SELECT 100*( SELECT COUNT(*) FROM table1 ) / ( SELECT COUNT(*) FROM table2 )
    AS percent;

否则,

function percent($num, $total)
{
    return number_format((100.0*$num)/$total, 2);
}

答案 1 :(得分:1)

我的猜测是这样的事情可能会起作用(请注意,我没有测试过,所以可能需要调整):

<?php

//TOTAL ENTRIES INTO Table 1 FOR total data
$result   = mysql_query("SELECT COUNT(*) AS total FROM table1");
$table1_total = mysql_result($result, 0);

 //TOTAL ENTRIES IN Table 2  FOR THE PERCENTAGE
$result2 = mysql_query("SELECT COUNT(*) AS total FROM table2");
$table2_total = mysql_result($result2, 0);

function percent($num_amount, $num_total) {
    $count1 = $num_amount / $num_total;
    $count2 = $count1 * 100;
    $count3 = 100 - $count2;
    $count = number_format($count3, 0);
    echo $count;
}

percent($table1_total, $table2_total);

答案 2 :(得分:0)

试试这个:

    <?php

    function percent($num_amount, $num_total) {
     $count1 = $num_amount / $num_total;
     $count2 = $count1 * 100;
     $count = number_format($count2, 0);
     echo $count2."<br>";
     }

     percent(50,100);
     percent(13,100);
     percent(13,200);

    ?>