Php Can';t访问数组成员

Php Can';t访问数组成员,php,arrays,Php,Arrays,我想不出来。我创建了一个简单的类,它返回一个数组数组。这是我们的班主任 class BlogComments { public $commentArray=array(); public $blogId; function __construct($inId) { if(!empty($inId)) { $this->blogId=$inId; $sql="select id,name,url,comment,email from blog_co

我想不出来。我创建了一个简单的类,它返回一个数组数组。这是我们的班主任

class BlogComments {
public $commentArray=array();
public $blogId;

function  __construct($inId) {
    if(!empty($inId)) {
        $this->blogId=$inId;
        $sql="select id,name,url,comment,email from blog_comment where blog_id=$inId";
        $link2=GetConnection();
        $query=mysql_query($sql,$link2) or die("Invalid blog id:".mysql_error());
        while($row=mysql_fetch_array($query)) {
            $this->commentArray=array(
                "id"=>$row['id'],
                "name"=>$row['name'],
                "url"=>$row['url'],
                "email"=>$row['email'],
                "comment"=>$row['comment']
            );
        }
        mysql_close($link2);
    }
}
}
我试图通过一个循环访问数组的每个成员。它正在进入循环,但返回的值为空。我已经确认数据正在写入阵列。这是我的密码

include "include/commentclass.php";
$comments = new BlogComments($post->id);
foreach($comments as $comment) {
    echo "<h4>".$comment->commentArray['name']."</h4>
        <a href=\"".$comment->commentArray['url']."\">".$comment->commentArray['url']."</a>
        <p>".$comment->commentArray['comment']."</p>";
}
include“include/commentclass.php”;
$comments=新博客评论($post->id);
foreach($comments作为$comment){
回显“.$comment->commentArray['name']”
“$comment->commentArray['comment']。”

”; }
基本上,它返回空标记。我还验证了$post->id持有有效值。知道我做错了什么吗

谢谢你的帮助, B

试试这个:

$comments = new BlogComments($post->id);
foreach ($comments->commentArray as $comment) {
    echo "<h4>".$comment['name']."</h4>
        <a href=\"".$comment['url']."\">".$comment['url']."</a>
        <p>".$comment['comment']."</p>";
}
$comments=新博客评论($post->id);
foreach($comments->commentArray作为$comment){
回显“.$comment['name']”
“$comment['comment']。”

”; }
new
关键字返回单个对象。除非您的对象(
blogcoments
)实现了
Traversable
foreach
将作用于公共属性
commentArray
blogId
,而不是
commentArray
内容


您还可以让您的类实现一个
迭代器接口。

您犯了一些错误,第一个错误是netcoder指出的:您将对象用作数组,而没有实现
迭代器接口。第二个是直接将结果数组分配给
$this->commentArray
。您应该通过以下方式将结果附加到数组:
$this->commentArray[]=array(

您不能对对象引用进行迭代。正如netcoder在其回答中所说的,您应该实现Traversable来实现这一点。或者只是在类中实现一个方法,该方法将为您提供$commentArray。感谢netcoder,我现在得到了一些值,但这很奇怪。它正在返回…55

然后tt

。注释id为5,而该id的名称以t开头。我不明白为什么会发生这种情况?你们都是对的。我需要按照你们所说的将结果附加到数组中,并且使用netcoders代码,我能够让这两个都工作。多亏了你们两个!+1@Minkiele:很好,我没有看到缺少的
[]