php - 如何映射从联接返回的匹配记录而不是单独的行

标签 php mysql sql codeigniter

场景:

我有两个表,结构如下。

表 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 中的 ma​​p() 函数,但无法实现这一点。

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/

相关文章:

javascript - 为什么在以下场景中没有设置 href 属性?

php - 如何将生成的字母数字字符串存储到数据库 phpmyadmin

mysql - 在 SQL 中使用表作为变量

mysql - 如何计算特定字段SQL中的特定字符

Java 8 中的 java.sql.Date 与 Java 6 的比较

php - Google Cloud SQL 和 PHP 教程不是在编辑数据库吗?

php - 如何在 Magento 仪表板图中显示挂单

mysql - 使用 SQL 查询以 CSV 格式导出 WordPress 帖子和元信息

从我的桌面到远程 MySQL 的 MySQL 连接无法正常工作

sql - 在管道分隔串联期间格式化列标题 (Oracle SQL)