您好,我正在尝试以列表的形式输出MySQL查询结果,以便在每隔五行之后创建一个新的列表。我按照之前对我的一个类似问题的建议做了同样的事情,它在第五行之后分离了结果,但在每个新列表中,第一个元素与前一个列表中的最后一个元素是相同的。
我使用了以下代码:
/*there is a mysqli query before this*/
$i = 0;
$count = $res->num_rows;
echo '<ul>';
while($obj = $res->fetch_object()){
$i++;
$exturl = $obj->link;
$extname = utf8_encode($obj->title);
echo '<li><a class="URL" title="'.$extname.'" href="'.$exturl.'" target="_blank">'.$extname.'</a></li>';
if($i % 5 == 0 && $i < $count){
echo '</ul><ul><li><a class="URL" title="'.$extname.'" href="'.$exturl.'" target="_blank">'.$extname.'</a></li>';
}
}
echo '</ul>';问题是,我怎样才能避免重复?
发布于 2012-10-26 05:47:29
在条件句中追加最后一个li有什么意义?
while($obj = $res->fetch_object()){
$i++;
$exturl = $obj->link;
$extname = utf8_encode($obj->title);
echo '<li><a class="URL" title="'.$extname.'" href="'.$exturl.'" target="_blank">'.$extname.'</a></li>';
if($i % 5 == 0 && $i > 0 && $i < $count){
echo '</ul><ul>';
}
}因为您已经在if $i %5语句上回显了它。
发布于 2012-10-26 05:49:34
解决方案(取决于返回的行数)可能是在呈现列表之前对结果进行分页( array_chunk ),从而产生一种简单的分页形式。
$results = array();
while ($obj = $res->fetch_object()) {
$results[]= $obj;
}
// Break results into sub-lists of 5 items
$lists = array_chunk($results, 5);
foreach ($lists as $list) {
echo "<ul>"
foreach ($list as $obj) {
$exturl = $obj->link;
$extname = utf8_encode($obj->title);
echo '<li><a class="URL" title="',$extname,'" href="', $exturl, '" target="_blank">', $extname, '</a></li>';
}
echo "</ul>"
}这需要您将整个结果集加载到内存中,但与尝试从单个循环中有条件地关闭和重新打开列表相比,这是一个清晰得多的解决方案。
发布于 2014-02-04 21:18:52
$args=array('orderby' => 'title','order' => 'ASC','posts_per_page'=>-1 ,'post_type'=>'Product');
$loop = new WP_Query($args);'
$counter = 1;
$reccounter=1;
$total_items = count($loop);
$ColCounter=($loop->post_count)/3;
if(!empty($loop)){
print '<ul style="float:left;list-style:none;" class="productList">';
while ( $loop->have_posts() ) : $loop->the_post();
$reccounter++;
$this_char=strtoupper(substr($loop->post->post_title,0,1));
if ($this_char != $last_char) { $last_char = $this_char;
$counter++;
echo '<h2 class="productTitle">'.$last_char.'</h2>';
}
if( $ColCounter<=$reccounter){echo "</ul><ul style='float:left;list-style:none;' class='productList'>";
$reccounter=1;
}
echo"<li class='productListpad'><a href=".get_permalink($loop->post->ID). "title=".esc_attr($loop->post->post_title ? $loop->post->post_title : $loop->post->ID).">".esc_attr($loop->post->post_title ? $loop->post->post_title : $loop->post->ID)."</a></li>";
endwhile; echo"</ul>";
}wp_reset_query(); https://stackoverflow.com/questions/13077808
复制相似问题