【问题标题】:Php foreach loop wrapping every 2 itemsPHP foreach 循环包装每 2 个项目
【发布时间】:2021-01-25 22:14:37
【问题描述】:
<div class="puffar">
        <?php
        //Set up the objects needed
        $my_wp_query = new WP_Query();
        $all_wp_pages = $my_wp_query->query(array('post_type' => 'page'));

        //Get children
        $children = ($post->post_parent) ? get_page_children( $post->post_parent, $all_wp_pages ) :  get_page_children( $post->ID, $all_wp_pages );

        $i = 0;
        //Build custom items 
        foreach($children as $child){ 
        $i++;

        /*
        if (i % 2 == 0) { ?>

        <?php
        } */
        ?>

<div class="col-sm-6">
    <div class="puff">
        <div class="puff-image-holder">
            <?php echo get_the_post_thumbnail( $child->ID, 'full' ); ?>
        </div>
        <fieldset class="linedHeadline hlmedium">
            <legend><?php echo get_the_title($child->ID); ?></legend>
        </fieldset>
        <?php echo get_field("puff_introtext", $child->ID); ?>
        <?php
        $values = get_field( 'puff_lanktext', $child->ID );
        if (get_field( "popup_eller_lank", $child->ID ) == "popup") {
        ?>
        <fieldset class="linedHeadline hlmedium">
            <legend><a class ="linktopage open-popup" href="<?php echo get_page_link($child->ID); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend>
        </fieldset>
        <?php
        } elseif (get_field( "popup_eller_lank", $child->ID ) == "extern") {
        ?>
            <fieldset class="linedHeadline hlmedium">
            <legend><a class ="linktopage" href="<?php echo get_field( "puff_lank", $child->ID ); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend>
        <?php
        } else { }
        ?>

    </div>
</div>

<?php } ?>
</div>

你好堆垛机!

我需要一些关于如何包装循环元素的 php 帮助。我想将 2 个元素包装在 &lt;div class="row"&gt;. 中,所以基本上是 &lt;row&gt; &lt;item&gt; &lt;item&gt; &lt;/row&gt;

如你所见,我已经尝试了一些模数,一些 if 语句仍然存在。我将 i 设置为 0,并试图在 1 % 2 = 0 时输入&lt;div class="row"&gt;,但没有找到关于如何正确关闭标签的解决方案(应该在第二项之后关闭) 作为一个新手 php 黑客,你有没有机会帮助我?

编辑:

    <div class="puffar">
        <?php
        //Set up the objects needed
        $my_wp_query = new WP_Query();
        $all_wp_pages = $my_wp_query->query(array('post_type' => 'page'));

        //Get children
        $children = ($post->post_parent) ? get_page_children( $post->post_parent, $all_wp_pages ) :  get_page_children( $post->ID, $all_wp_pages );

        $i = 0;
        //Build custom items 
        echo "<div class='row'>";
        foreach($children as $child){   
        ?>

<div class="col-sm-6">
    <div class="puff">
        <div class="puff-image-holder">
            <?php echo get_the_post_thumbnail( $child->ID, 'full' ); ?>
        </div>
        <fieldset class="linedHeadline hlmedium">
            <legend><?php echo get_the_title($child->ID); ?></legend>
        </fieldset>
        <?php echo get_field("puff_introtext", $child->ID); ?>
        <?php
        $values = get_field( 'puff_lanktext', $child->ID );
        if (get_field( "popup_eller_lank", $child->ID ) == "popup") {
        ?>
        <fieldset class="linedHeadline hlmedium">
            <legend><a class ="linktopage open-popup" href="<?php echo get_page_link($child->ID); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend>
        </fieldset>
        <?php
        } elseif (get_field( "popup_eller_lank", $child->ID ) == "extern") {
        ?>
            <fieldset class="linedHeadline hlmedium">
            <legend><a class ="linktopage" href="<?php echo get_field( "puff_lank", $child->ID ); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend>
        <?php
        $i++;  
        if ($i % 2 == 0) { 
            echo "</div><div class='row'>";
        }
        } else { }
        ?>
    </div>
</div>

<?php } ?>
</div>
</div>

这只会包装我所有的循环项目,我希望 div class=row 只包装每 2 个项目

【问题讨论】:

    标签: php


    【解决方案1】:

    你快到了:

        //Build custom items 
        echo "<row>";
        $i = 0;
        foreach($children as $child) { 
    
            echo "item "; 
    
            $i++;  
            if ($i % 2 == 0 && $i != count($children)) { 
                echo "</row><row>";
            }
    
        }
        echo "</row>"
    

    【讨论】:

    • 请看一下我的代码的最后一行。您需要在循环之后关闭div ,而else 部分是不必要的。
    • 完美运行。请将此标记为答案。谢谢。
    【解决方案2】:

    或者这个:

    <?php
    $i=0;
    foreach($children as $child){ 
        ++$i;
        if($i==1){
            echo "<row>";
            echo "<item>$child</item>";
        }
        if($i==2){
            echo "<item>$child</item>";
            echo "</row>"
            $i=0;
        }
    }
    

    [更新]

    这让我很烦恼:奇数个孩子可能会导致没有结束标签的一行。 虽然大多数浏览器只会在渲染上添加标签,你根本不会有任何问题,但这仍然不是 100% 正确的。

    在计算奇数子节点时,您可能需要在 foreach 循环之后进行检查和结束行,如下所示:

    if($i==1){
        echo "</row>";
    }
    

    如果 $i == 1 在循环之后,这是一个奇数的孩子,该行必须关闭。

    [/更新]

    【讨论】:

    • 非常简单的解决方案。我实际上使用了它,它对于包括奇数在内的未知数量的项目效果最好。干得好。
    • THX,我认为它的可读性最强,是什么让代码比花哨的天才代码寿命更长,没有人可以阅读。
    • 太棒了!聪明!
    【解决方案3】:

    您应该像这样使用for 循环而不是foreach 循环:

    for($i = 0; $i < count($children); $i+=2) {
        $child1 = $children[$i];
        $child2 = $children[$i+1];
        // print both
    }
    

    如果您可能有奇数个孩子,您必须在打印之前检查$i+1 &lt; count($children)

    【讨论】:

    • 不要在比较中使用count($children),这会导致性能问题。像这样写for($i = 0, $count=count($children); $i &lt; $count; $i+=2)
    • @ArturStępień 这不是在做完全相同的事情,而且还将计数分配给变量吗?我原以为您应该在 for 循环之外分配 count 变量。
    • @RobertWent 不,它没有。在第一次交互之前处理循环中第一个 ; 之前的内容。每次交互都会比较您在条件中所拥有的内容,最后(在最后一次; 之后)在每次交互之后处理您所拥有的内容。所以你应该在循环之前创建$count 变量,或者像我一样做。
    • @ArturStępień 我现在看到了,感谢您的澄清!
    • @RobertWent 没问题的人,一只小海豹就去救了 XD
    【解决方案4】:

    这是在 Wordpress 中,但理解它,它会帮助你。

    <?php $query = new WP_Query( array( 'post_type' => 'slides', 'order'=> 'DESC', 'post_status' => 'publish', 'posts_per_page' => -1) );
                   $posts = $query->posts; 
                   $numOfCols = 2;
                    $rowCount = 0;
                   if(!empty($posts)){ ?>
    
                       <div class="carousel-item <?php echo ($numOfCols-1==1)?'active':''; ?>">
                        <div class="row"> 
    
                          <?php foreach ($posts as $post) { ?>
                            <div class="col-md-6 pt-4 pb-0 " >
                               <h6 class="mb-2 text-uppercase"><b><a href="<?php echo get_permalink( $post->ID); ?>" target="_blank"><?php echo $post->post_title; ?></a></b></h6>
                               <span><?php echo get_the_excerpt($post->ID); ?></span><span class="float-right"><a href="<?php echo get_permalink( $post->ID); ?>" target="_blank"><i _ngcontent-ttx-c19="" class="material-icons icon-image-preview" style="position: relative;  top: 7px;">arrow_forward</i></a></span>
                            </div>
    
                          <?php 
                          $rowCount++; 
                          if($rowCount % $numOfCols == 0 && $rowCount != count($posts)) echo '</div></div><div class="carousel-item "><div class="row"> ';
                        } ?>
    
                    </div>
                      </div>
        <?php }  ?>
    

    【讨论】:

      【解决方案5】:
      # Process every second item starting with the first one [0].
      foreach ($array as $key => $value) {
          if (($key - 1) % 2 === 0) {
              continue;
          }
      
          # Do something here.
      
      }
      

      【讨论】:

      • 虽然此代码可能会为问题提供解决方案,但最好添加有关其工作原理/方式的上下文。这可以帮助未来的用户学习并将这些知识应用到他们自己的代码中。在解释代码时,您也可能会以赞成票的形式从用户那里获得积极的反馈。
      【解决方案6】:

      试试这个

      $i = 1;
              //Build custom items
              foreach($children as $child){
              if($i>2){
               $i =1;
              }
      
              if ($i==2) {
                 //close row
              }
             $i++;
         }
      

      【讨论】:

        猜你喜欢
        • 2020-06-05
        • 2012-10-27
        • 1970-01-01
        • 1970-01-01
        • 2012-12-28
        • 1970-01-01
        • 1970-01-01
        • 2015-11-04
        • 2018-03-24
        相关资源
        最近更新 更多