mysql获取多层嵌套json_使用两个mySQL查询来创建嵌套的JSON数组

本文介绍如何使用两个MySQL查询来构建一个包含评论及其相关回复的嵌套JSON数组。通过首先获取所有评论,然后针对每条评论查询其对应的回复,将回复数据动态添加到评论数据中。在实现过程中遇到了将对象作为数组使用的错误,需要找到正确的方法将回复数据整合到评论数据的嵌套结构中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我正尝试创建一个嵌套的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[''.$c->id] = $c;

if($replies){

foreach($replies as $r){

// The line below causes the problem

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

}

}

}

echo json_encode( $output );正如你可以看到我试图做的是检索查询-1的结果,通过它们并填充数组。到现在为止还挺好。然后对结果集中的每一行执行第二个查询,使用$ 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"

}]

},它目前是二维的,但没有“答复”。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值