0

I have the following php code:

    $k=1;
    for($i=0; $i < 5; $i++)
    {
        $stmt = $db->query('SELECT * FROM services_main');
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

            if ($row['ID'] == $i) {

                for($j=1; $j <= 3; $j++)
                {
                    echo $row['name'].' - k='.$k++.'<br />';
                }

            }
        }
    }

This code generates this:

    John - k=1
    John - k=2
    John - k=3
    Paul - k=4
    Paul - k=5
    Paul - k=6
    George - k=7
    George - k=8
    George - k=9

What i am trying to do it have it generate this:

    John - k=1
    John - k=1
    John - k=1
    Paul - k=2
    Paul - k=2
    Paul - k=2
    George - k=3
    George - k=3
    George - k=3

I can't figure out how to make k increment for each grouping as opposed to incrementing on every single line.

Thanks in advance for your help!

4

3 回答 3

0

替换这个:

for($j=1; $j <= 3; $j++)
            {
                echo $row['name'].' - k='.$k++.'<br />';
            }

有了这个

for($j=1; $j <= 3; $j++)
            {
                echo $row['name'].' - k='.$k.'<br />';
            }
$k++;
于 2012-06-22T16:34:08.960 回答
0

k++外面的while循环。

$k=1;
for($i=0; $i < 5; $i++)
{
    $stmt = $db->query('SELECT * FROM services_main');
    while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

        if ($row['ID'] == $i) {

            for($j=1; $j <= 3; $j++)
            {
                echo $row['name'].' - k='.$k.'<br />';
            }

        }
    }
    $k++;
}
于 2012-06-22T16:33:40.613 回答
0

不要在每次通过内部“for”循环时递增 $k,而是在每次“while”循环迭代时递增一次:

for($j=1; $j <= 3; $j++)
{
    echo $row['name'].' - k='.$k.'<br />';
}
$k++;
于 2012-06-22T16:33:52.573 回答