Php 使用两个mySQL查询创建嵌套JSON数组
我试图创建一个嵌套的JSON数组,将第二个查询的结果附加到第一个查询的行 我的代码如下:-Php 使用两个mySQL查询创建嵌套JSON数组,php,mysql,json,Php,Mysql,Json,我试图创建一个嵌套的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
$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 );
正如您所看到的,我试图做的是检索query-1的结果,遍历它们并填充一个数组。到现在为止,一直都还不错。然后,对于resultset中的每一行,执行第二个查询,使用$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"
}]
},
它目前是二维的,但是没有“回复”。$output['comment-'。$c->id]是一个对象。我想你想要像这样的东西
$output['comment-'.$c->id]->回复[]=$r $output['comment-'.$c->id]是一个对象。我想你想要像这样的东西 $output['comment-'.$c->id]->回复[]=$r