我正在尝试从 MYSQL 查询中返回一个嵌套数组。我有一个帖子、用户、关键字和类别表,我想优化查询,所以我没有太多选择。我目前SELECT
对一篇文章有 4 个查询,每个查询都循环一个foreach
,并在 PHP 中创建一个嵌套数组。有没有办法将这些整合到更少的查询中,并更快地执行?
这是一排的样子。关键字、类别和作者编号都是它们各自表中的 id。
帖子表:
| id | title | content | keywords | category | author |
|----|-------|----------------|----------|----------|--------|
| 1 | Test | Lorem ipsum... | 1, 2 | 1 | 1 |
|----|-------|----------------|----------|----------|--------|
关键词表:
| id | name | url | description |
|----|----------|----------|----------------|
| 1 | keyword1 | keyword1 | Lorem ipsum... |
| 2 | keyword2 | keyword2 | Lorem ipsum... |
|----|----------|----------|----------------|
用户表:
| id | name | email |
|----|----------|--------------|
| 1 | John Doe | john@doe.com |
|----|----------|--------------|
类别表:
| id | name | url |
|----|-----------|-----------|
| 1 | Category1 | category1 |
|----|-----------|-----------|
这是我想要实现的输出:
Array
(
[0] => Array
(
[id] = 1
[title] = Test
[content] = Lorem ipsum dolor sit amet, consectetur adipisicing elit. Alias, sapiente assumenda ratione dicta cumque accusantium id labore cupiditate maiores obcaecati repudiandae at eum fuga doloremque commodi. Quidem, nulla cupiditate aperiam!
[keywords] => Array
(
[0] => Array
(
[id] => 1
[name] => keyword1
[url] => keyword1
[description] => Lorem ipsum dolor sit amet, consectetur adipisicing elit. Asperiores, dolorem, consectetur voluptatem amet hic placeat alias rerum unde quis quia aperiam officia aliquam incidunt sit fugit quo iusto porro repellat!
)
[1] => Array
(
[id] => 2
[name] => keyword2
[url] => keyword2
[description] => Lorem ipsum dolor sit amet, consectetur adipisicing elit. Magnam, culpa, repudiandae voluptatibus odit nam id sed maxime ullam quia accusamus minima nisi! Dolor, doloremque similique voluptatibus at eos vitae id?
)
)
[category] => Array
(
[id] => 1
[name] => Category1
[url] => category1
)
[author] => Array
(
[id] => 1
[name] => John Doe
[email] => john@doe.com
)
)
)