2012-01-16 107 views
0

我有下面的代碼。 $ related是數據庫查詢的數組結果,包含數據。PHP Foreach with UL groups and LI

查詢數據包含屬於不同組的帖子(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(); 

回答

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>'; 
} 
+0

謝謝你這爲我工作:) – unfulvio 2012-01-16 05:01:02