我刚开始与PHP MongoDB,我想做的是从数据库中获取数据,并自动调用它创建个人后div。但是在我实现了下面的代码之后,它只显示了最近的一个,而不是我实际得到的集合中的所有三个文档…
下面是函数的代码,我知道这是一个非常基本的错误(可能):function get_posts($cursor){
while ($cursor->hasNext()) {
$entry = $cursor->getNext();
$blog_body = "";
$blog_body = $blog_body . '<div class="wrap-it">';
$blog_body = $blog_body . '<div class="jumbotron">';
$blog_body = $blog_body . '<div class="container">';
$blog_body = $blog_body . "<h2>" . $entry['title'] ."</h2>";
$blog_body = $blog_body . "<p>". $entry['description'] ."</p>";
$blog_body = $blog_body . '<p><a class="rec-btn">Read more »</a></p>';
$blog_body = $blog_body . '</div></div></div>';
}
return $blog_body;
}
And被这样调用:
<?php $posts = get_posts($cursor);
echo $posts; ?>
问题出在$blog_body =" "(将其移到while循环之前):
function get_posts($cursor){
$blog_body = "";
while ($cursor->hasNext()) {
$entry = $cursor->getNext();
$blog_body = $blog_body . '<div class="wrap-it">';
$blog_body = $blog_body . '<div class="jumbotron">';
$blog_body = $blog_body . '<div class="container">';
$blog_body = $blog_body . "<h2>" . $entry['title'] ."</h2>";
$blog_body = $blog_body . "<p>". $entry['description'] ."</p>";
$blog_body = $blog_body . '<p><a class="rec-btn">Read more »</a></p>';
$blog_body = $blog_body . '</div></div></div>';
}
return $blog_body;
}
在这一行中,您将为每个新迭代重置$blog_body内容。
$blog_body = "";
这样说
function get_posts($cursor) {
$blog_body = "";
while ($cursor->hasNext()) {
$entry = $cursor->getNext();
$blog_body .= '<div class="wrap-it">';
$blog_body .= '<div class="jumbotron">';
$blog_body .= '<div class="container">';
$blog_body .= "<h2>" . $entry['title'] ."</h2>";
$blog_body .= "<p>". $entry['description'] ."</p>";
$blog_body .= '<p><a class="rec-btn">Read more »</a></p>';
$blog_body .= '</div></div></div>';
}
return $blog_body;
}