【问题标题】:PHP Foreach with UL groups and LI带有 UL 组和 LI 的 PHP Foreach
【发布时间】:2012-02-11 03:29:53
【问题描述】:

我有下面的代码。 $related 是数据库查询的数组结果,包含数据。

查询的数据由属于不同组的帖子(post_type)组成。我想将查询的对象分组到它们的 post_type 中。下面的代码可以工作,但是......我想要的是为每个 post_type 创建不同的 UL。如下所示,在查询中找到的每个帖子都会有一个 UL 元素。所以 UL 应该远离 foreach,但另一方面,我怎样才能让 post_type 脱离 foreach?我在这里有点迷路:(

$related = p2p_type( 'accommmodation-to-places' )->get_connected( get_queried_object_id() ); 
foreach($related->posts as $post) {
    echo '<ul class="related-'.$post->post_type.'">'; // this shouldn't be here
    if($post->post_type == 'hotels') {
        echo '<li><a href="'.get_permalink($post->ID).'" rel="permalink">'.get_the_post_thumbnail($post->id, '48').$post->post_title.'</a></li>';    
    }
    echo '</ul>'; // this shouldn't be here
}
wp_reset_query();

【问题讨论】:

    标签: php if-statement for-loop foreach html-lists


    【解决方案1】:

    首先,将帖子按类型分组

    $groups = array();
    foreach ($related->posts as $post) {
        $groups[$post->post_type][] = $post;
    }
    

    然后遍历组并输出列表:

    foreach ($groups as $type => $posts) {
        printf('<ul class="%s">', htmlspecialchars($type));
        foreach ($posts as $post) {
            printf('<li>...</li>', ...);
        }
        echo '</ul>';
    }
    

    【讨论】:

      猜你喜欢
      • 2013-05-14
      • 1970-01-01
      • 2011-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多