首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >while循环中的前端循环

while循环中的前端循环
EN

Stack Overflow用户
提问于 2013-09-25 12:58:49
回答 2查看 1.9K关注 0票数 0

我正在尝试将wordpress标记(和其他输入)转换为html类。首先,我查询这些帖子,将它们设置在一个while循环中,在这个while循环中,我将标记转换为有用的类。我现在得到了这个:

代码语言:javascript
复制
 <?php while ($query->have_posts()) : $query->the_post(); 


    $posttags = get_the_tags();
    if ($posttags) {
      foreach($posttags as $tag) {
        $thetags =  $tag->name . ''; 
        echo $the_tags;

        $thetags = strtolower($thetags);


        $thetags = str_replace(' ','-',$thetags);
        echo $thetags;


      }
   }
    ?>

    <!-- Loop posts -->         
    <li class="item <?php echo $thetags ?>" id="<?php the_ID(); ?>" data-permalink="<?php the_permalink(); ?>">

<?php endwhile; ?>

现在有什么问题:

第一个回波,回音标签像:标签1标签2,第二个回音像标签-1标签-2,什么不是我想要的,因为每个标签之间没有空格。因此,它只是html类中显示的最后一个标记,因为它不在foreach循环中。

我想要什么:,我想在html类中拥有所有相关的标记。因此,最终的结果必须是:

代码语言:javascript
复制
<li class="item tag-1 tag-2 tag-4" id="32" data-permalink="thelink">

但是,如果我将列表项放在foreach循环中,我将为每个标记获得一个<li>项。如何正确地做这件事?谢谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-09-25 13:09:44

我会这样做(使用数组代替它,然后使用内爆获得它之间的空格:)

代码语言:javascript
复制
<?php while ($query->have_posts()) : $query->the_post(); 

$tags = array(); // a array for the tags :)
$posttags = get_the_tags();
if (!empty($posttags)) {
  foreach($posttags as $tag) {
    $thetags =  $tag->name . ''; 
    echo $the_tags;

    $thetags = strtolower($thetags);


    $thetags = str_replace(' ','-',$thetags);
    $tags[] = $thetags;

    echo $thetags;


  }
}
?>

<!-- Loop posts -->      
<li class="item <?= implode(" ", $tags) ?>" id="<?php the_ID(); ?>" data-permalink="<?php the_permalink(); ?>">
票数 1
EN

Stack Overflow用户

发布于 2013-09-25 13:03:37

使用数组代替,然后implode它。帮你自己一个忙,在你的while子句中用括号代替(如果你更喜欢它的可读性-我知道在这种情况下是这样的):

代码语言:javascript
复制
<?php
    while ($query->have_posts()) {
        $query->the_post(); 

        $posttags = get_the_tags();

        $tags = array(); //initiate it
        if ($posttags) {
            foreach($posttags as $tag) {
                $tags[] = str_replace(' ','-', strtolower($tag->name)); //Push it to the array
            }
        }
        ?>
            <li class="item<?php echo (!empty($tags) ? ' ' . implode(' ', $tags) : '') ?>" id="<?php the_ID(); ?>" data-permalink="<?php the_permalink(); ?>">
        <?php
    }
?>
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19005636

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档