PHP Foreach与UL组和LI

时间:2012-01-16 04:34:47

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

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

查询的数据包含属于不同组的帖子(post_type)。我想在post_type中对查询过的对象进行分组。下面的代码工作但是...我想要的是为每个post_type创建不同的UL。如下所示,查询中将找到一个UL元素foreach帖子。所以UL应该远离foreach,但另一方面,我怎样才能从foreach中获得post_type?我在这里有点迷失:(

$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();

1 个答案:

答案 0 :(得分:3)

首先,按照类型分组帖子:

$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>';
}