【问题标题】:Is this normal for a foreach inside a foreach?这对于 foreach 中的 foreach 是否正常?
【发布时间】:2016-12-13 10:55:18
【问题描述】:

这是我下面的代码。它使用array_chunk() 将结果分成三组,所以每个.row 只有3 列。

   <?php
    $blogusers = get_users( 'exclude=1,12'); //WordPress's get_users()
    $split = array_chunk($blogusers,3); 

    // Array of WP_User objects.
    foreach ( $split as $user ) { 

        echo '<div class="row">';


          foreach ($user as $details){ 

            // get user profile picture or default to a plain one
            if (get_field('show', 'user_'.$details->ID)){ 
              $img = get_field('profile_pic','user_'.$details->ID); 
            }

          echo
           //output each user
           '<div class="columns small-4">
              <div class="profile">
                <div class="profile-image-wrap">      
                  <img src="'.$img.'" class="team-image">
                  <a href="" class="profile-hover-link"><i class="fa fa-bars fa-bars fa-3x"></i></a>      
                </div>    
                <div class="profile-details-wrap">
                  <h4>'.$details->display_name.'</h4>
                  <h5>'.the_field('title', 'user_'.$details->ID).'</h5>
                  <div class="hr-wrap">
                    <hr class="team-hr">
                  </div>                                
                  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam aliquam massa quis mauris sollicitudin commodo.</p>
                  <a class="view" href="">view profile</a>
                </div>
              </div>
            </div>';               
          }
        echo '</div>'; 
      }

问题出在这一行

&lt;h5&gt;'.the_field('title', 'user_'.$details-&gt;ID).'&lt;/h5&gt;

它不会将输出插入到 &lt;h5&gt; 标记中,如下所示。

我尝试在该行上使用双引号和单引号,但这并不能解决问题。

我该如何解决这个问题?

【问题讨论】:

    标签: php html wordpress advanced-custom-fields


    【解决方案1】:

    我想你正在使用Advanced Custom Fields plugin。如果您查看docs for the_field,您会看到它

    显示指定字段的值。该功能与echo get_field($field_name);相同

    这正是您想要的。在您的情况下,您希望函数返回字段的值,而不是打印它。所以,把你的行改为

    <h5>'.get_field('title', 'user_'.$details->ID).'</h5>
    

    你可以走了。

    您的问题是您在将其打印到浏览器之前构建了一个字符串。在此构建阶段,您将调用the_field,它会执行自己的echoing。这就是标题出现在整个 div 之前的原因。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-24
      • 2017-01-02
      • 1970-01-01
      • 1970-01-01
      • 2011-01-14
      • 2013-09-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多