我需要创建一个通用方法/算法来为这种数据结构创建层次结构:
获取结果的查询是这样的:
SELECT
*
FROM
`Posts`
JOIN
`Comments` AS `Comments`
ON
`Posts`.`post_id` = `Categories`.`category_id`
JOIN
`Likes` AS `Likes`
ON
`Comments`.`comment_id` = `Likes`.`comment_id`
我的期望是这样的:
Array
(
[0] => Array
(
[post_id] => 1
[post_message] => Test
[Comments] => Array
(
[0] => Array
(
[comment_id] => 1
[post_id] => 1
[comment_message] => Foo
[Likes] => Array
(
[0] => Array
(
[like_id] => 1
[comment_id] => 1
)
[1] => Array
(
[like_id] => 2
[comment_id] => 1
)
)
)
[1] => Array
(
[comment_id] => 2
[post_id] => 1
[comment_message] => Bar
[Likes] => Array
(
[0] => Array
(
[like_id] => 3
[comment_id] => 2
)
)
)
)
)
)
所以我的问题是: 使用PDO有一种简单的方法吗?我可以手动遍历数组,从information_schema获取密钥,创建子数组,还有更多的子数组...,但这就像再次手动编写连接一样。
我注意到,在调用PdoStatements fetchAll()时可以使用一个常量:
$statement->fetchAll(PDO::FETCH_ASSOC | PDO::FETCH_GROUP);
将在一定程度上对数据进行分组,但不是我想要的方式。
那么这是一个常数吗(或类似的东西),或者你知道fetchAll的任何聪明的回调,会这样做吗?