我有这样的db结构。
create table article(
id int AUTO_INCREMENT PRIMARY KEY,
title varchar(50),
text text
)
create table comments(
id int AUTO_INCREMENT PRIMARY KEY,
article int not null
username varchar(30) not null,
text text not null,
foreign key(article) references article(id) on delete cascade
)
我想得到带有注释的文章 然后用这个结构转换成json。
[
{
id: 1,
title: "article1",
text: "text1",
"comments": [
{
id: 1,
username: "user1",
text: "text"
}
]
}
]
这是我的代码:
$query = $pdo->query('select * from article as a join comments as c on c.article =a.id');
$query->execute();
var_dump(json_encode($query->fetchAll(PDO::FETCH_ASSOC)));
和结果:
[{"id":"1","title":"artile1","text":"comment1","article":"1","username":"user1"}]
有什么办法可以将文章和评论作为内数组?我可以手动操作,但是,我将有很多表,有很多列。
谢谢你的建议
看起来使用PDO获取模式是不可能的。它们很强大,但不幸的是,我无法得到你想要的输出。
你可以使用一个简单的循环来实现这个结果。缺点是你必须手动创建数组。
$stmt = $pdo->prepare('SELECT a.id AS aid, a.title, a.text AS atext, c.id AS cid, c.username, c.text AS ctext
FROM article AS a
JOIN comments AS c ON c.article =a.id ');
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$id = null;
$data = [];
foreach ($stmt as $row) {
$comment = [
'id' => $row['cid'],
'username' => $row['username'],
'text' => $row['ctext'],
];
if ($id == $row['aid']) {
// If parent ID still the same append only comment
$data[array_key_last($data)]['comments'][] = $comment;
} else {
// set new id and append a whole new row
$id = $row['aid'];
$data[] = [
'id' => $row['aid'],
'title' => $row['title'],
'text' => $row['atext'],
'comments' => [$comment]
];
}
}
PDO有很多取数模式,你可以把它们混合在一起,但是看起来没有一个能像你希望的那样处理连接。这些模式在这里都有描述 https:/phpdelusions.netpdofetch_modes。