0

这对于专家来说可能相当简单,但作为新手,我需要帮助。我有以下三个表,其中包含项目和附件。我希望将这些数据填充到一个多维数组中,如下面的结果部分中给出的(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 中进行编码,以便获得上述结果。非常感谢您提前。

4

1 回答 1

0

如果您真的得到要插入 JSON 的数据,请查看json_decode
将数据存储在变量中后,您可以使用foreach循环遍历它,并为每个循环适当地插入数据。

于 2012-11-14T20:35:16.837 回答