2012-01-10 68 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