-1

在下面的示例中,我正在提取六个随机行,并希望将变量之一(a、b、c、d、e、f)分配给每个生成的行。

$result = mysql_query("SELECT * FROM cub_posts WHERE active = 'Y' ORDER BY rand() LIMIT 6") or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
    $demo_id = 'a, b, c, d, e, f';

    echo '<div class="span4 span-box">
    <div id="demo5'.$demo_id.'" class="ho-box demo5">'.$row['title'].'</div>
    </div>';
}

所以输出将是:

<div class="span4 span-box">
<div id="demo5a" class="ho-box demo5">Title</div>
</div>
<div class="span4 span-box">
<div id="demo5b" class="ho-box demo5">Title</div>
</div>
<div class="span4 span-box">
<div id="demo5c" class="ho-box demo5">Title</div>
</div>
<div class="span4 span-box">
<div id="demo5d" class="ho-box demo5">Title</div>
</div>
<div class="span4 span-box">
<div id="demo5e" class="ho-box demo5">Title</div>
</div>
<div class="span4 span-box">
<div id="demo5f" class="ho-box demo5">Title</div>
</div>
4

4 回答 4

1

将演示移到循环之外

$demo_id = array('a', 'b', 'c', 'd', 'e', 'f');  
$counter;
while ($row = mysql_fetch_array($result)) { 
    echo '<div class="span4 span-box">
    <div id="demo5'.$demo_id[$counter].'" class="ho-box demo5">'.$row['title'].'</div>
    </div>';
    $counter++;
}

但是,如果您有超过 6 个结果,它将失败。Demo id 可以包含所有字母:

$demo_id = range("a","z");
于 2013-01-11T20:57:45.480 回答
1

尽管你不应该使用mysql_njk 很好地总结的函数,但不难想出一些处理前 26 行的东西:

$demo_id = 'a';
while ($row = mysql_fetch_array($result)) { 
 echo '<div class="span4 span-box">';
 echo '<div id="demo5'.$demo_id.'" class="ho-box demo5">'.$row['title'].'</div>';
 echo '</div>';
 ++$demo_id;
}

但是你需要考虑当超过 26 个时会发生什么。

于 2013-01-11T20:57:57.663 回答
1

您可以添加一个计数器。

$result = mysql_query("SELECT * FROM cub_posts WHERE active = 'Y' ORDER BY rand() LIMIT 6") or die(mysql_error());

$demo_id = array('a', 'b', 'c', 'd', 'e', 'f');  

$i=0;

while ($row = mysql_fetch_array($result)) { 

echo '<div class="span4 span-box">
<div id="demo5'.$demo_id[$i].'" class="ho-box demo5">'.$row['title'].'</div>
</div>';

 $i++;
}
于 2013-01-11T21:04:21.983 回答
0
$char = 97
while ($row = mysql_fetch_array($result)) {
    echo '<div class="span4 span-box">';
    echo '<div id="demo5'.chr($char).'" class="ho-box demo5">'.$row['title'].'</div>';
    echo '</div>';
    $char++;
}
于 2013-01-11T21:02:54.437 回答