php - MySQL选择多维?
问题描述
我想从我的数据库中选择所有帖子及其附件。
这是带有虚拟数据的结构:
帖子表
id | post | userId |
---------|---------------|----------|
1 | "hello" | 1 |
2 | "world" | 1 |
3 | "ouch" | 2 |
4 | "test" | 1 |
附件表
id | postId | fileName | time |
---------|---------------|----------|----------|
1 | 1 |"hey.jpg" | 0 |
2 | 1 |"test.png"| 53252354 |
3 | 2 |"asd.png" | 0 |
4 | 4 |"asd2.png"| 0 |
到目前为止,我的代码看起来像这样,但我并没有真正得到我想要的。
$qry = $db->prepare('
SELECT p.id
, p.post
, p.userId
, att.fileName
, att.time
FROM posts p
LEFT
JOIN attachments att
ON att.postId = p.id
');
$qry->execute();
$postsArray = $qry->fetchAll(PDO::FETCH_ASSOC);
我想要这样的东西:
[{'id': 1,
'post': 'hello',
'userId': 1,
'attachments': [{'fileName': 'hey.jpg', 'time:' 0}, ... ]
}, ... ]
我怎么能做到这一点?
解决方案
您的查询将为您提供所需结果的正确数据,您可以在 PHP 中进行后处理以获得所需的格式:
foreach ($postArray as $post) {
$fixed_part = array('id' => $post['id'], 'post' => $post['post'], 'userId' => $post['userId']);
$key = serialize($fixed_part);
if (!isset($out[$key])) $out[$key] = $fixed_part;
$out[$key]['attachments'][] = array('fileName' => $post['fileName'], 'time' => $post['time']);
}
$out = array_values($out);
echo json_encode($out, JSON_PRETTY_PRINT);
推荐阅读
- .net - 生成相对于 DateTime 的数字
- android - 合并错误:错误:android 28.0.3 中的属性 application@appComponentFactory
- objective-c - 不兼容的块指针类型将“void (^_Nullable)(enum MyReturnCode)”发送到“void (^)(enum MyReturnCode)”类型的参数
- ios - 如何检查 UIScrollView 内容是否不需要使用滚动
- c++ - RtlCaptureStackBackTrace 未捕获任何帧
- java - java.lang.ClassCastException:com.ethanhua.skeleton.SkeletonAdapter 无法转换为 me.tatarka.bindingcollectionadapter2.BindingRecyclerViewAdapter
- python - 如何从 Python 中的 CSV 文件中删除非重复项?
- c# - 如何正确序列化 .net 4.7.[x]+ 和 .net Standard 2.[x]+ 中的异常
- c# - 映射 FallbackRoute 时如何添加 SwaggerUI
- javascript - 工作日数组 [mon,wed,thu,fri,sun] 以字符串形式显示,例如 mon,wed-fri,sun