【发布时间】:2016-03-14 09:47:05
【问题描述】:
我正在为博客文章获取所有 cmets,我还通过使用以下函数的引用将它们放在树结构中:
public function getComments($articleID) {
$sql = "SELECT * FROM comments WHERE articleid = $articleID";
$database = DatabaseFactory::getFactory()->Connect();
$stmt = $database->query($sql);
$res = $stmt->fetchAll(PDO::FETCH_ASSOC);
if($res!=NULL)
{
$references = array();
$tree = array();
foreach ($res as $id=> &$node) {
// Use id as key to make a references to the tree and initialize it with node reference.
$references[$node['comment_id']] = &$node;
// Add empty array to hold the children/subcategories
$node['children'] = array();
// Get your root node and add this directly to the tree
if ($node['comment_respond_to']==0) {
$tree[$node['comment_id']] = &$node;
} else {
// Add the non-root node to its parent's references
$references[$node['comment_respond_to']]['children'][$node['comment_id']] = &$node;
}
}
return $tree;
当我print_r($tree);这是输出;
Array
(
[1] => Array
(
[comment_id] => 1
[articleid] => 1
[user_id] => 2
[comment_comment] => First comment.
[comment_date] => 2016-03-10 20:06:43
[comment_respond_to] => 0
[children] => Array
(
[2] => Array
(
[comment_id] => 2
[articleid] => 1
[user_id] => 1
[comment_comment] => First comment, first child.
[comment_date] => 2016-03-10 20:06:43
[comment_respond_to] => 1
[children] => Array
(
)
)
[4] => Array
(
[comment_id] => 4
[articleid] => 1
[user_id] => 1
[comment_comment] => First comment, second child.
[comment_date] => 2016-03-10 20:06:43
[comment_respond_to] => 1
[children] => Array
(
)
)
)
)
[3] => Array
(
[comment_id] => 3
[articleid] => 1
[user_id] => 2
[comment_comment] => Second comment.
[comment_date] => 2016-03-10 20:06:43
[comment_respond_to] => 0
[children] => Array
(
[6] => Array
(
[comment_id] => 6
[articleid] => 1
[user_id] => 1
[comment_comment] => Second comment, first child.
[comment_date] => 2016-03-10 20:06:43
[comment_respond_to] => 3
[children] => Array
(
)
)
)
)
)
一切都很完美。
是时候回声了。
我想要的输出:
- 第一条评论
- 第一个评论,第一个孩子。
- 第一个评论,第二个孩子。
- 第二条评论
- 第二条评论,第一个孩子。
所以,我知道我的下一步应该是使用 foreach 创建循环并获取 cmets。
我将return $tree; 替换为;
foreach ($tree as $key) {
echo '<li>'.$key["comment_comment"], '</li>';
}
它输出;
- 第一条评论
- 第二条评论
儿童 cmets 丢失。 我知道我的下一步应该是在当前 foreach 中创建另一个 foreach 以获取子 cmets,但我不知道该怎么做。
感谢您的帮助。
【问题讨论】:
标签: php