使用涉及关系表的mySQL查询填充多维数组

时间:2012-11-14 20:23:47

标签: php mysql json relational-database

对于专家来说这可能相当简单,但作为新手我需要帮助。我有以下三个表,其中有项目和&附件。我想将这些数据填充到多维数组中,如下面的结果部分所示(采用JSON格式)。

Tables - columns

items
- itemID
- itemTitle
- catID

attachments
- attachmentID
- itemID
- attachmentFilename

考虑到数据库中有两个项目,第一个项目与2个附件相关,第二个项目与3个附件相关,这就是我希望看到结果的方式:

{
    "items": [{
        "item": {
            "itemID": "1",
            "itemTitle": "The first item",
            "attachments": [{
                "attachment": {
                    "attachmentFilename": "The First attachment.att",
                    "attachmentID": "1"
                },
                "attachment": {
                    "attachmentFilename": "The Second attachment.att",
                    "attachmentID": "2"
                }
            }]
        }
    },
    {
        "item": {
            "itemID": "2",
            "itemTitle": "The Second item",
            "attachments": [{
                "attachment": {
                    "attachmentFilename": "The Third attachment.att",
                    "attachmentID": "3"
                },
                "attachment": {
                    "attachmentFilename": "The Fourth attachment.att",
                    "attachmentID": "4"
                },
                "attachment": {
                    "attachmentFilename": "The Fifth attachment.att",
                    "attachmentID": "5"
                }
            }]
        }
    }]
}

我想知道如何在php中编码,以便我得到上述结果。非常感谢你提前。

1 个答案:

答案 0 :(得分:0)

如果您确实要在JSON中插入数据,请查看json_decode 一旦您的数据存储在变量中,您就可以使用foreach遍历它,并为每个循环插入适当的数据。