2012-01-10 124 views
1

我想創建一個嵌套的JSON數組,並將第二個查詢的結果連接到第一個的行。使用兩個mySQL查詢來創建嵌套的JSON數組

到目前爲止我的代碼如下: -

$output = array(); 

$sql = "select cp_comments.*,users.user_login from ".$wpdb->prefix."cp_comments cp_comments 
       left join ".$wpdb->prefix."users users on users.ID=cp_comments.uid 
       where songid='$id' 
       order by cp_comments.id asc";    
    $comments = $wpdb->get_results($sql); 



    foreach($comments as $c){ 


     $sql = "select cp_replies.*,users.user_login from ".$wpdb->prefix."cp_replies cp_replies 
        left join ".$wpdb->prefix."users users on users.ID=cp_replies.uid 
        where cp_replies.cid='".$c->id."' 
        order by cp_replies.id asc"; 
     $replies = $wpdb->get_results($sql); 


    $output['comment-'.$c->id] = $c;   


     if($replies){ 

      foreach($replies as $r){ 

      // The line below causes the problem 
      //$output['comment-'.$c->id][] = $r; 


      }  
     }   
    } 

    echo json_encode($output); 

正如你可以看到,我試圖做的是檢索查詢-1的結果,通過他們LOP和填充數組。到現在爲止還挺好。然後對結果集中的每一行執行第二個查詢,使用$ c-> id作爲變量來動態更改依賴於id的第二個查詢,然後將這些數據嵌套到第一個查詢的每個返回行中。

我註釋掉行導致錯誤: -

Fatal error: Cannot use object of type stdClass as array in 

雖然我爲什麼這個錯誤發生的一個大概的瞭解,我不知道如何解決它,當我已經嘗試了標準使用while循環的多維數組等,然後我無法訪問$ c - > $ id變量,使整個第二個查詢變得毫無價值。

基本上我想在這種格式返回的數據: -

{ "comment-2" : [ { "avatar" : "http://www.songbanc.com/wp-content/uploads/avatars/1/8bb11e958a26913e2c13393014e854d5-bpthumb.jpg", 
     "body" : "More tests....", 
     "display_name" : "admin", 
     "id" : "26", 
     "playtime" : 36.206896551699998, 
     "posttime" : "2011-10-08 11:11:55", 
     "cid" : "26", 
     "songid" : "30", 
     "uid" : "1", 
     "user_login" : "admin", 
     "user_url" : "http://www.songbanc.com/members/admin/" 
     "cid": "1", 
     "replies" : [ { "cid" : "26", 
         "body" : "test reply", 
         "posttime" : "2011-10-08 11:11:55" 
         }] 

     }, 

這是目前二維但是沒有「答覆」。

回答

1

$ output ['comment - '。$ c-> id]是一個對象。我想你想要類似

$ output ['comment - '。$ c-> id] - >回覆[] = $ r;

+0

有多尷尬......這個問題解決了。非常感謝。 :-) – gordyr 2012-01-10 01:33:51