2012-09-05 25 views
3

我有一個由三個查詢返回的帖子數組。 帖子位於「媒體」或「洞察」中的帖子不在「媒體」或「洞察」中的3篇帖子,帖子位於「洞察」中的帖子位於「媒體中」 3的帖子中的帖子。PHP:需要循環來替換返回的文章

這是我的。我不認爲這是最優雅的解決方案:

<? $args = array(
    'post_type' => 'post', 
    'posts_per_page' => 3, 
    'category__not_in' => array(268, 269) 
); 
$homePosts = new WP_Query($args); 

$args = array(
    'post_type' => 'post', 
    'category_name' => 'in-the-media', 
    'posts_per_page' => 3 
); 
$inthemediaPosts = new WP_Query($args); 

$args = array(
    'post_type' => 'post', 
    'category_name' => 'bt-insights', 
    'posts_per_page' => 3 
); 
$insightsPosts = new WP_Query($args); 

$allqueries = array($homePosts,$inthemediaPosts,$insightsPosts); 
foreach ($allqueries as $myquery) { 
    while ($myquery->have_posts()) : $myquery->the_post(); ?> 

目前,通過3個homeposts循環,那麼3發inthemedia的帖子,然後3 BT-見解的帖子。

我需要的是讓循環遍歷1個homepost,1個媒體文章,1個bt-insight帖子,然後是1個homepost,1個inthemediea post ...等等。

希望是有道理的。建議?

+0

請看看這個問題中描述的自定義用戶函數[array_zip_merge()](http://stackoverflow.com/questions/1860490/interleaving-multiple-arrays-into-a-single-array),這個將允許您合併三個不同的數組,交替每個數組中的值。這種方法對於你想達到的效果綽綽有餘 – Scuzzy

+0

@Scuzzy,'$ myquery'似乎不是一個數組,雖然... – Mischa

+0

我假設可以完成以下工作:foreach( array_zip_merge($ homePosts,$ inthemediaPosts,$ insightsPosts)as $ myquery) – Scuzzy

回答

0

如果去掉allqueries的東西,以後有什麼:

$insightsPosts = new WP_Query($args); 

只要用這個代替。

for ($i = 0; $i < 3; $i++) { 
    if ($homePosts->post_count > $i) 
     echo $homePosts->posts[$i]->post_title; 
    if ($inthemediaPosts->post_count > $i) 
     echo $inthemediaPosts->posts[$i]->post_title; 
    if ($insightsPosts->post_count > $i) 
     echo $insightsPosts->posts[$i]->post_title; 
} 

這應該只是打印出帖子的標題,您可以根據需要使用其他字段。這可以轉移到一個函數,以避免重複邏輯。

0
while($allqueries[0]->have_posts() || $allqueries[1]->have_posts() || $allqueries[2]->have_posts()) { 
    if ($allqueries[0]->have_posts()) $allqueries[0]->the_post(); 
    if ($allqueries[1]->have_posts()) $allqueries[1]->the_post(); 
    if ($allqueries[2]->have_posts()) $allqueries[2]->the_post(); 
}