2012-01-10 4 views
1

2番目のクエリの結果を最初の行に添付して入れ子にしたJSON配列を作成しようとしています。次のように2つの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に応じて2番目のクエリを動的に変更し、最初のクエリの各返された行内にこのデータをネストします。

私がコメントアウトしている行は、エラーの原因: -

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

私はこのエラーが起こっている理由の大まかな理解しているが、私はそれを修正する方法がわからないと、私は標準を試してみましたときwhileループなどを使用した多次元配列では、$ c - > $ id変数にアクセスすることができず、2番目のクエリ全体が役に立たなくなりました。

は基本的に私はこの形式で返されたデータをたいと思います: -

{ "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" 
         }] 

     }, 

それはしかし、「回答」することなく、現在2次元です。

答えて

1

$ output ['comment - '。$ c-> id]はオブジェクトです。あなたのようなものがほしいと思う。

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

+0

どのように恥ずかしい...それはそれを修正しました。どうもありがとう。 :-) – gordyr

関連する問題