2

我试图从另一个获取 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 变量不返回任何信息。

任何想法或建议将不胜感激。

谢谢

斯坦

4

3 回答 3

7

您回显结果,但您不会从函数中返回它。这大概就是问题所在。

但是,您可以全部在 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);
}
于 2012-09-23T21:18:34.783 回答
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);
于 2012-09-23T21:20:55.857 回答
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);

    ?>
于 2012-09-23T21:23:48.527 回答