2014-09-03 56 views
0

我正嘗試爲php構建一個自定義的json feed。無法循環通過類別循環內的帖子。只獲得第一個項目

它已經完成,你可以看到。

問題是,通過帖子循環只輸出同一類別的一個項目。

這裏是我的PHP代碼:

<?php 
    header("Content-type: application/json"); 

    class Item { 
     public $id = ""; 
     public $title = ""; 
     public $thumb = ""; 
    } 

    class Category { 
     public $id = ""; 
     public $title = ""; 
     public $item = array(); 
    }  

    $finalData = array(); 
    //Get sub-categories from 'news' 
    $idObj = get_category_by_slug('news'); 
    $id = $idObj->term_id; 
    $cat_args=array(
     'orderby' => 'id', 
     'order' => 'ASC', 
     'parent' => $id 
    ); 

    $categories=get_categories($cat_args); 

    //Loop through categories 
    foreach($categories as $category) { 
     $args=array(
      'showposts' => 10, 
      'category__in' => array($category->term_id), 
      'caller_get_posts'=>1 
     ); 
     $posts=get_posts($args); 
     $a = new Category(); 
     $a->id = $category->term_id; 
     $a->title = $category->name; 
     $arrayForItems = array(); 

     //Loop through first 10 posts from this categorie 
     if ($posts) { 
      $actualItem = $arrayForItems[] = new Item(); 
      $actualItem->id = get_the_ID(); 
      $actualItem->title = get_the_title(); 
      $img = wp_get_attachment_image_src(get_post_thumbnail_id(get_the_ID()), 'appthumb'); 
      $actualItem->thumb = $img; 
     } 
     $a->item = $arrayForItems; 
     $finalData[] = $a; 
    }; 

    echo json_encode($finalData); 
?> 

任何想法?謝謝。

回答

2

那是因爲你說只打印一次。添加一個while語句應該工作:

$count = 0; 
while($count < 10) 
{ 
    if ($posts) { 
      $actualItem = $arrayForItems[] = new Item(); 
      $actualItem->id = get_the_ID(); 
      $actualItem->title = get_the_title(); 
      $img = wp_get_attachment_image_src(get_post_thumbnail_id(get_the_ID()), 'appthumb'); 
      $actualItem->thumb = $img; 
    } 
    $count++; 
} 

編輯:這應該工作

foreach ($posts as $post): 
setup_postdata($post); 
     //Loop through first 10 posts from this categorie 
     if ($posts) { 
      $actualItem = $arrayForItems[] = new Item(); 
      $actualItem->id = get_the_ID(); 
      $actualItem->title = get_the_title(); 
      $img = wp_get_attachment_image_src(get_post_thumbnail_id(get_the_ID()), 'appthumb'); 
      $actualItem->thumb = $img; 
     } 
     $a->item = $arrayForItems; 
     $finalData[] = $a; 
endforeach; 
+1

foreach循環更適合這種情況下,不是嗎? – 2014-09-03 10:41:43

+0

謝謝Howlin。現在,我可以爲每個類別獲得10個帖子,但帖子總是相同的!任何想法? – 2014-09-03 10:45:24

+0

@RafaelMartins,檢查我的編輯,應該工作。 – Howli 2014-09-03 11:42:46

相關問題