dougu9895 2014-11-18 21:10
浏览 22
已采纳

PHP计算循环生成的结果

I have this for loop that generates 10 results:

    <?php

    include "dbconnect.php";

    $table = "SELECT id FROM players ORDER BY RAND()* ( 1 / percentage)";

    for ($i = 0; $i < 10; $i++){

        $result[0] = mysql_fetch_array(mysql_query($table));

        foreach ($result as $winner){

            echo $winner[0] . " ";

        }

    }


?> 

It generates a result like:

10 10 11 9 13 11 10 12 8 12

My question is how do I count the generation? For the above example it would be:

8's = 1, 9's = 1, 10's = 3, 11's = 2, 12's = 2, 13's = 1.

I basically want to count the amount of specific results generated. Sorry if i'm not making much sense.

  • 写回答

2条回答 默认 最新

  • dongmu5920 2014-11-18 21:19
    关注

    You need to get off of MySQL functions and check out PDO or MySQLI at a minimum. But for the meat of the question:

    1. Don't run a query, full or limited in the loop
    2. Look at the LIMIT clause in the query
    3. array_count_values will count the values. You can loop it and echo or whatever

    Example:

    $table  = "SELECT id FROM players ORDER BY RAND()*(1/percentage) LIMIT 10";
    $result = mysql_query($table);
    
    while($row = mysql_fetch_array($result)) {
        $winner[] = $row[0];
    }
    echo implode(' ', $winner);
    
    foreach(array_count_values($winner) as $number => $count) {
        $output = "$number's = $count";
    }
    echo implode(', ', $output);
    

    You're existing code to make the random choice work would look like (LIMIT 1):

    $table = "SELECT id FROM players ORDER BY RAND()*(1/percentage) LIMIT 1";
    
    for($i = 0; $i < 10; $i++){
        $result = mysql_fetch_array(mysql_query($table));
        $winner[] = $row[0];
    }
    echo implode(' ', $winner);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向