【问题标题】:A foreach loop in a while loopwhile 循环中的 foreach 循环
【发布时间】:2013-10-01 02:05:51
【问题描述】:

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

 <?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。第二个回显它像 tag-1tag-2,这也不是我想要的,因为每个标签之间没有空格。因此只有最后一个标签显示在 html 类中,因为它不在 foreach 循环中。

我想要什么: 我想在 html 类中有所有相关的标签。所以最终的结果一定是这样的:

<li class="item tag-1 tag-2 tag-4" id="32" data-permalink="thelink">

但是,如果我将列表项放在 foreach 循环中,我会为每个标签获得一个 &lt;li&gt; 项。如何正确执行此操作?谢谢!

【问题讨论】:

  • 你有多个标签,所以使用数组来存储多个标签

标签: php wordpress foreach while-loop


【解决方案1】:

我会做这样的事情(使用数组而不是那个,然后使用 implode 来获取它,它之间有空格:)

<?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(); ?>">

【讨论】:

  • 你可以像 h2ooooooo 显示的那样删除一些回声并将一些东西放在一行上(你甚至不需要这个( $thetags = $tag->name .''; )因为你可以只需这样做 $thetags = $tag->name;
【解决方案2】:

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

<?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
    }
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-19
    • 2016-03-14
    • 2017-05-28
    • 2023-04-09
    • 2012-10-02
    • 2014-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多