修正:在我的数据库中,如果Parent是emty是0而不是NULL,那么我将if ($comment['Parent'] === NULL)
更改为if ($comment['Parent'] < 1)
,它现在可以正常工作了。如果有人想要使用此功能,我也会将$results = $ROW
更改为$results[] = $ROW
。
由于
我正在尝试为我的应用程序实现一个线程注释类。但是我收到了一个错误:
警告:第25行Z:\ Projects \ icerik \ html \ test.php中的非法字符串偏移'Parent' 警告:第31行的Z:\ Projects \ icerik \ html \ test.php中的非法字符串偏移'Parent'
数据库是CommensID - 评论 - 父 - ContentID
这是原始代码code
这是print_r($results);
显示的内容
Array (
[CommentsID] => 131
[ContentID] => 1171
[UserID] => 668
[Comment] => hic birsey yapmamislar. bu programdan sonra spor haberleri sunmus. yalanincada olmus.
[Time] => 0000-00-00 00:00:00
[Parent] => 130
[WriterIP] => 82.11.180.115
[Active] => 1
[TotalVotes] => 0
[VoteSum] => 0
)
以下是代码:
<?php
//database connection
class Threaded_comments
{
public $parents = array();
public $children = array();
/**
* @param array $comments
*/
function __construct($comments)
{
foreach ($comments as $comment)
{
if ($comment['Parent'] === NULL)
{
$this->parents[$comment['CommentsID']][] = $comment;
}
else
{
$this->children[$comment['Parent']][] = $comment;
}
}
}
/**
* @param array $comment
* @param int $depth
*/
private function format_comment($comment, $depth)
{
for ($depth; $depth > 0; $depth--)
{
echo "--";
}
echo $comment['Comment'];
echo "<br />";
}
/**
* @param array $comment
* @param int $depth
*/
private function print_parent($comment, $depth = 0)
{
foreach ($comment as $c)
{
$this->format_comment($c, $depth);
if (isset($this->children[$c['CommentsID']]))
{
$this->print_parent($this->children[$c['CommentsID']], $depth + 1);
}
}
}
public function print_comments()
{
foreach ($this->parents as $c)
{
$this->print_parent($c);
}
}
}
$sql = $dbc->prepare("SELECT * FROM comments WHERE ContentID = 1171");
$sql->execute();
$results = array();
while($ROW = $sql->fetch(PDO::FETCH_ASSOC))
{
$results = $ROW;
}
$threaded_comments = new Threaded_comments($results);
$threaded_comments->print_comments();
?>
答案 0 :(得分:0)
更改以下代码。我认为这应该适合您。
$results = array();
while($ROW = $sql->fetch(PDO::FETCH_ASSOC))
{
$results[] = $ROW;
}
将$results = $ROW;
更改为$results[] = $ROW;
警告显示是因为:
foreach ($comments as $comment)
{
// Here **$comment** should not be an array according to your code
// Your code goes here
}
所以你可以这样做:
foreach ($comments as $key => $value)
{
if($key == 'Parent') {
$this->parents[$comments[$key]][] = $comments;
} else {
}
// Your code goes here
}