已修复:在我的数据库中,如果父项为空,则为 0 而非 NULL,所以我更改了 if ($comment['Parent'] === NULL)
至if ($comment['Parent'] < 1)
现在可以了。我也改$results = $ROW
至$results[] = $ROW
如果有人想使用这个。
谢谢
我正在尝试为我的应用程序实现一个线程注释类。但我收到错误:
Warning: Illegal string offset 'Parent' in Z:\Projects\icerik\html\test.php on line 25
Warning: Illegal string offset 'Parent' in Z:\Projects\icerik\html\test.php on line 31
数据库是 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();
?>
最佳答案
更改以下代码。我认为这应该适合您。
$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
}
关于php - 线程注释类给我数组错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18357212/