我想使用json在我的MySQL(PDO)中发送3个表。第一个表中有一个循环 注意: 第一个表(fetchAll) 第二张表(获取) 第三表(获取)
$stmt1 = $db->prepare("SELECT * FROM data WHERE countid='1'");
$stmt1->execute();
$data = $stmt1->fetchAll(PDO::FETCH_OBJ);
$stmt2 = $db->prepare("SELECT id,title FROM weeks WHERE id='2'");
$stmt2->execute();
$data->weeks[] = $stmt2->fetch(PDO::FETCH_OBJ);
$stmt3 = $db->prepare("SELECT id,name FROM user WHERE id='1'");
$stmt3->execute();
$data->user[] = $stmt3->fetch(PDO::FETCH_OBJ);
$response = new stdClass();
$response->data[] = $data;
echo json_encode($response);

如何将其发送到此格式:
{"data":[
{"title":"name of module1",
"description":"description of module1",
"weeks":[{"id":1,"title":"Week 01"}],
"user":[{"id":1,"name":"george"}]
},
{"title":"name of module2",
"description":"description of module2",
"weeks":[{"id":2,"title":"Week 02"}],
"user":[{"id":2,"name":"john"}]
}
]
}

数据:id,name,content,user_id,week,countid;
周: id,data_id,checkin,checkout;
用户: ID,用户名,姓名,姓氏;
( data.id == weeks.data_id )和( data.user_id == user.id )相同..
答案 0 :(得分:1)
好的,现在需要更多的代码。您必须获取所有data
行,然后使用其中的键从其他2个表中获取相关行。
$stmt = $db->prepare("SELECT * FROM data WHERE countid='1'");
$stmt->execute();
$datas = $stmt->fetchAll(PDO::FETCH_OBJ);
foreach ( $datas as $key => &$data ) {
// get related weeks data
$stmt = $db->prepare("SELECT id,title FROM weeks WHERE data_id=:id ORDER BY id");
$stmt->execute( array(':id'=>$data->id) );
$data->weeks = $stmt->fetchAll(PDO::FETCH_OBJ);
// get related user data
$stmt = $db->prepare("SELECT id,name FROM user WHERE id=:id ORDER BY id");
$stmt->execute( array(':id'=>$data->user_id) );
$data->user = $stmt->fetchAll(PDO::FETCH_OBJ);
}
echo json_encode( array('data'=>$datas) );
结果:
{
"data": [
{
"id": 1,
"title": "name of module1",
"description": "description of module 1",
"user_id": 1,
"week": "1",
"countid": 1,
"weeks": [
{
"id": 1,
"title": "Week 01"
}
],
"user": [
{
"id": 1,
"name": "chris"
}
]
},
{
"id": 2,
"title": "name of module 2",
"description": "description of module 2",
"user_id": 2,
"week": "2",
"countid": 1,
"weeks": [
{
"id": 2,
"title": "Week 02"
}
],
"user": [
{
"id": 2,
"name": "john"
}
]
}
]
}