场景:
我有两个表,结构如下。
表 1:图像
+--------+------------+
| img_id | img_name |
+--------+------------+
| 1 | image1.jpg |
| 2 | image2.jpg |
| 3 | image3.jpg |
+--------+------------+
表 2:image_tags
+---------+--------+----------+--------+--------+
| cord_id | img_id | tag_text | xcord | ycord |
+---------+--------+----------+--------+--------+
| 1 | 1 | Tag1 | 28.1 | 30.4 |
| 2 | 1 | Test Tag | 23.4 | 4.5 |
+---------+--------+----------+--------+--------+
现在我想要图像及其标签,使用左连接非常简单
SELECT img_id, img_name,tag_text, xcord,ycord FROM images t1 LEFT JOIN image_tags t2 ON t1.id=t2.id
此查询产生以下数据集
+--------+------------+----------+--------+--------+
| img_id | img_name | tag_text | xcord | ycord |
+--------+------------+----------+--------+--------+
| 1 | image1.jpg | Tag1 | 28.1 | 30.4 |
| 1 | image1.jpg | Test Tag | 23.4 | 4.5 |
| 2 | image2.jpg | NULL | NULL | NULL |
| 3 | image3.jpg | NULL | NULL | NULL |
+--------+------------+----------+--------+--------+
问题:
现在使用 PHP(或 MYSQL,如果可能),我希望将 image_tags 表中的结果以数组的形式与每一行连接起来。 这样,当我循环遍历 Angular 中的记录时,我会看到图像及其标签以数组的形式,而不是两个单独的行,因为您可以看到结果集中的前两行。
期望的结果示例,
{
cord_id : 1,
img_id : 1,
tags : [{
tag_text : "Tag1",
xcord : 28.1,
ycord : 30.4,
},{
tag_text : "Test Tag",
xcord : 23.4,
ycord : 4.5,
}
]
}
我研究过 PHP 中的 map() 函数,但无法实现这一点。
Note: I am using Codeigniter, so if that has some relevant support to achieve this, that would also work for me.
任何帮助将不胜感激。谢谢
最佳答案
只需一个查询即可完成此操作。
由于您有一个唯一的 ID,因此您可以将其用作数组的索引。
$images = array();
foreach($queryResults as $result){
if(!isset($images[$result['img_id']])){
$images[$result['img_id']] = array();
$images[$result['img_id']]['cord_id'] = $result['cord_id'];
$images[$result['img_id']]['img_id'] = $result['img_id'];
$images[$result['img_id']]['tags'] = array();
}
$tag = array(
'tag_text'=>$result['tag_text'],
'xcord'=> $result['xcord'],
'ycord'=> $result['ycord']
);
$images[$result['img_id']]['tags'][] = $tag;
}
关于php - 如何映射从联接返回的匹配记录而不是单独的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36098535/