gpt4 book ai didi

php - 循环遍历记录集(PHP + MySQL),将列表项中的每 2 条记录分组

转载 作者:行者123 更新时间:2023-11-29 09:00:14 24 4
gpt4 key购买 nike


我需要循环遍历一个记录集(PHP + MySQL),将每 2 条记录分组到一个列表项中

我的实际代码(简化)是这样的:

<?php
// how many total records do I have?
mysql_select_db($database_connEIB, $connEIB);
$query_rsMediaCount = "SELECT COUNT(*) AS med_count FROM media";
$rsMediaCount = mysql_query($query_rsMediaCount, $connEIB) or die(mysql_error());
$row_rsMediaCount = mysql_fetch_assoc($rsMediaCount);

$mCount = $row_rsMediaCount['med_count']; // total records
$mPages = ceil($mCount / 2); // max LIs to create
$mIndex = 0; // useful initialization for LIMIT, see below

if ($mCount > 0) { // let's show markup only if there's some record!
?>
<ul>
<?php for ($mPage = 1; $mPage <= $mPages; $mPage++) { // create the LIs ?>
<li>
<?php
$query_rsMedia = "SELECT med_id FROM media LIMIT $mIndex, 2";
$rsMedia = mysql_query($query_rsMedia, $connEIB) or die(mysql_error());
$row_rsMedia = mysql_fetch_assoc($rsMedia);
do { ?>
<div><?php echo $row_rsMedia['med_id']; ?></div>
<?php } while ($row_rsMedia = mysql_fetch_assoc($rsMedia));
$mIndex += 2; // increment the LIMIT by 2 steps ?>
</li>
<?php } ?>
</ul>
<?php } ?>

输出排序如下:

<ul>
<li>
<div>1</div>
<div>2</div>
</li>
<li>
<div>3</div>
<div>4</div>
</li>
<li>
<div>5</div>
</li>
</ul>

一切正常,但是有没有更优雅或更有效的解决方案?提前致谢

最佳答案

仅执行一次查询并将结果分组在循环内。使用模运算符%:

$query_rsMedia = "SELECT med_id FROM media";
$rsMedia = mysql_query($query_rsMedia, $connEIB) or die(mysql_error());

if (mysql_num_rows($rsMedia) > 0) { // check if there is at least one result
echo '<ul>';
$index = 0;
while ($row_rsMedia = mysql_fetch_assoc($rsMedia)) {
if ($index % 2 == 0) echo '<li>'; // open <li> bevore even result
echo '<div>'.$row_rsMedia['med_id'].'</div>';
if ($index % 2 == 1) echo '</li>'; // close <li> after odd result
$index++;
}
if ($index % 2 == 1) echo '</li>'; // close <li> if odd result count
echo '</ul>';
}

(只是写的,不是测试)

关于php - 循环遍历记录集(PHP + MySQL),将列表项中的每 2 条记录分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8850931/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com