我有以下查询:
$sth = $this->db->prepare("SELECT * FROM comment WHERE status = 1");
$sth->setFetchMode(PDO::FETCH_ASSOC);
$sth->execute();
$reviews = array();
while($row = $sth->fetch()){
$reviews[]['name'] = $row['name'];
$reviews[]['comment'] = $row['comment'];
$reviews[]['star'] = $row['star'];
}
return $reviews;
}
返回var_dump($this->reviews)
的以下内容:
array(9) {
[0]=> array(1) { ["name"]=> string(5) "name1" }
[1]=> array(1) { ["comment"]=> string(8) "comment1" }
[2]=> array(1) { ["star"]=> string(1) "4" }
[3]=> array(1) { ["name"]=> string(5) "name2" }
[4]=> array(1) { ["comment"]=> string(8) "comment2" }
[5]=> array(1) { ["star"]=> string(1) "4" }
[6]=> array(1) { ["name"]=> string(5) "name3" }
[7]=> array(1) { ["comment"]=> string(8) "comment3" }
[8]=> array(1) { ["star"]=> string(1) "4" }
}
如何使用foreach
按行显示name
,comment
,star
?
即:
name1, email1@email.com, comment1
name2, email2@email.com, comment2
name3, email3@email.com, comment3
我知道它应该是这样的:
foreach( $this->reviews as $key){
echo "Name:". $this->reviews['name'] . "Email:" . $this->reviews['email'] . "Comment:" . $this->reviews['comment'];
}
但这给了我Notice: Undefined index: name
。如何定义索引?
答案 0 :(得分:1)
您需要生成一个数组数组。像
这样的东西while($row = $sth->fetch()){
$reviews[] = array('name' => $row['name'], 'comment' => $row['comment'], 'star'=> $row['star']);
}
现在,您的$reviews
对象的元素数量与查询结果中的行数一样多,您可以按照自己的方式打印它。
至于打印(我认为是您的错误消息来源):
foreach($reviews as $thisValue) {
echo "Name: ". $value['name'];
}
应该有用。
答案 1 :(得分:1)
您正在错误地设置插入数组:
while($row = $sth->fetch()){
$reviews[]['name'] = $row['name'];
$reviews[]['comment'] = $row['comment'];
$reviews[]['star'] = $row['star'];
}
简写[]
每次都插入一个新元素,你想要实际插入一个数组作为元素。
while($row = $sth->fetch()){
$revArr=array('name' => $row['name'], 'comment' => $row['comment'], 'star' => $row['star']);
$reviews[]=$revArr;
}
编辑:现在将您的第二个foreach更改为:
foreach( $this->reviews as $key){
echo "Name:". $key['name'] . "Email:" . $key['email'] . "Comment:" . $key['comment'];
}
答案 2 :(得分:0)
您应该像这样使用foreach
循环:
foreach( $this->reviews as $value){
echo "Name:". $value['name'] . "Email:" . $value['email'] . "Comment:" . $value['comment'];
}
请注意我如何在循环中使用$value
而不是$this->reviews
。
答案 3 :(得分:0)
foreach( $this->reviews as $key){
echo "Name:". $this->reviews['name'] . "Email:" . $this->reviews['email'] . "Comment:" . $this->reviews['comment'];
}
这不是正确的方法,因为现在你正在使用$ key所以写 -
foreach( $this->reviews as $key){
echo "Name:". $key['name'] . "Email:" . $key['email'] . "Comment:" . $key['comment'];
}
答案 4 :(得分:0)
你可以这样做:
$reviews = array();
while($row = $sth->fetch()){
$reviews[] = array($row['name'], $row['comment'], $row['email'], $row['star']);
}
然后你可以做一个heredoc:
$str = '';
foreach( $this->reviews as $review ){
$str .=<<<html
name: {$review['name']}
email: {$review['email']}
comment: {$review['comment']}
start: {$review['star']}
html;
}
最后我回应了一切:
echo $str;
我认为这更清晰,你可以添加任何HTML。