迭代查询并将数字分组

时间:2017-05-27 13:58:16

标签: php html mysql loops

我正在为游戏编写脚本。它应该遍历查询并打印数字组。在每组中,有9个数字。例如,如果mysql_num_rows($sql_pp);返回16,则所有内容应如下所示:

  1. 1,2,3,4,5,6,7,8,9。
  2. 10,11,12,13,14,15,16。
  3. 我的代码:

    <?php
    ob_start();
    session_start();
    Header("Content-Type: text/html;charset=UTF-8");
    require_once($_SERVER['DOCUMENT_ROOT']."/data/conn_file.php");
    
    $login = $_SESSION['login'];
    $laukai = mysql_query("SELECT tb_pole.num, tb_pole.type, tb_pole.time AS tb_pole_time,
        tb_time.time AS tb_time_time FROM `tb_pole` JOIN tb_time ON tb_pole.type =
        tb_time.type WHERE `username` = '$login' ORDER BY tb_pole.time");
    $sql_pp = mysql_query("SELECT * FROM `tb_pole` WHERE `username` = '$login'") or
        die(mysql_error());
    $kol_pole = mysql_num_rows($sql_pp);
    $koll = $kol_pole / 9;
    
    if ($kol_pole <= 8) {
        $kl = 1;
    } else {
        $kl = 1;
        while ($kl <= $koll) {
            $kl++;
        }
    }
    ?>
    <table>
    <?php
    if (mysql_num_rows($laukai) > 0) {
        for ($i = 1; $i<=$kl; $i++) {
            while ($row = mysql_fetch_assoc($laukai))  {
    ?>
                <tr>
                    <td><?php echo $i; ?></td>
                    <td><?php echo $row['num']; ?></td>
                </tr>
        <?php
            }
        }
    }
    ?>
    

    它显示了这个:enter image description here

    如您所见,最后一行是1 | 10。它应该是2 | 10(因为数字10在第2组中)(使用&#34;检查元素&#34;)从1更改为2 enter image description here

    当我的变量$i不在while循环中时,我正在使用这些代码行:

    <div id="tabs_pole">
    <ul>
    <?php
        for($i = 1; $i <= $kl; $i++) {
    ?>
            <li><a href="#pole<?=$i; ?>"><span><?=$i; ?></span></a></li>
    <?php
        }
    ?>
    </ul>
    </div>
    

    一切都运转正常:enter image description here。 如何使用while循环实现这一目标?

2 个答案:

答案 0 :(得分:0)

如果您只想让号码按每9组分组,那么

<?php
if (mysql_num_rows($laukai) > 0) {
        $i=1;
        while ($row = mysql_fetch_assoc($laukai))  {
?>
            <tr>
                <td><?php echo floor($i/9)+1; ?></td>
                <td><?php echo $row['num']; ?></td>
            </tr>
    <?php
        $i++;
        }
    }
}
?>

$i只是记录编号并使用round处理它,其中1/9将给0加1给出1.对于10,这将是(10/9)+1 = 2 ......

答案 1 :(得分:0)

我找到了我的解决方案:)谢谢大家的帮助:)

SELECT CONCAT(people.firstName, ' ', people.lastName) as Name, 
people.emailAddress,
(CASE questions.fruit 
    WHEN 'apple' THEN 'YES'
    ELSE ''
END) as Apple,
(CASE questions.fruit 
    WHEN 'orange' THEN 'YES'
    ELSE ''
END) as Orange,
(CASE questions.fruit 
    WHEN 'banana' THEN 'YES'
    ELSE ''
END) as Banana
From answers
Join questions ON answers.attackID = campaign.attackID 
JOIN employees ON campaign.employee = employees.employeeID 
WHERE campaign.campaignID = '24' 
ORDER BY employees.employeeID