php - 使用 php 迭代器接口(interface)遍历数据库结果

标签 php mysql iterator spl

我一直在研究关于 php 的这本书,并且有一个关于使用迭代器接口(interface)的迭代器模式的示例。我可以使用迭代器接口(interface)循环遍历简单的数组,但我不太理解书中举例说明的内容。我将发布代码片段。它说而不是做这样的事情。

<?php
$posts = getAllPosts(); //example function return all post ids of this author
for($i = 0; $i<count($posts); $i++) 
{
$title = getPostTitle($post[$i]);
echo $title;
$author = getPostAuthor($post[$i]);
$content = parseBBCode(getPostContent($post[$i]));
echo "Content";
$comments = getAllComments($post[$i]);
for ($j=0; $j<count($comments); $j++)
{
$commentAuthor = getCommentAuthor($comments[$j]);
echo $commentAuthor;
$comment = getCommentContent($comments[$j]);
echo $comment;
}
}
?>

我们可以实现迭代器接口(interface)来提供更有效的东西

<?php
class Posts implements Iterator
{
private $posts = array();
public function __construct($posts)
{
if (is_array($posts)) {
$this->posts = $posts;
}
}
public function rewind() {
reset($this->posts);
}
public function current() {
return current($this->posts);
}
public function key() {
return key($this->var);
}
public function next() {
return next($this->var);
}
public function valid() {
return ($this->current() !== false);
}
}
?>

“现在让我们使用刚刚创建的迭代器。”

<?
$blogposts = getAllPosts();
$posts = new Posts($posts);
foreach ($posts as $post)
{
echo $post->getTitle();
echo $post->getAuthor();
echo $post->getDate();
echo $post->getContent();
$comments = new Comments($post->getComments());
//another Iterator for comments, code is same as Posts
foreach ($comments as $comment)
{
echo $comment->getAuthor();
echo $comment->getContent();
}
}
?>

现在我不明白为什么从未使用过 $blogposts,为什么它不是任何类方法的一部分,以及它会返回什么类型的数据,数组还是对象。

我也不明白 $post->getTitle() 是如何实现的。我会理解 $post['title']$posts->getTitle() 因为我们可以添加一个 getTitle() 方法帖子类。

我真的很想在我正在做的事情上复制这样的东西

foreach($key as $value) {
    $value->getTitle();
}

代替

foreach($key as $value) {
    $value['title'];
    //or
    $key->getTitle()
}

最佳答案

好像打错了,我觉得应该是

$blogposts = getAllPosts();
$posts = new Posts($blogposts);

关于对 getTitle 方法的访问,我需要更多代码才能正确回答这个问题......但是如果函数“getAllPosts”返回一个实现方法“getTitle()”的 Post 对象数组,我就会工作

希望对您有所帮助!

关于php - 使用 php 迭代器接口(interface)遍历数据库结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44992079/

相关文章:

c++ - 在 C++ 中的模板函数中初始化自动(未知)类型的 vector

phpseclib 即使在简单的命令上也不返回任何结果

javascript - Prestashop 产品定制 - 保存到购物车

两个查询之间的mysql变量

java - 以优雅的方式检查两个参数是否为 null

java - 返回没有Remove方法的迭代器

php - 你如何对 php 和 sql 数组进行排序?

php - 在接收到所有数据之前呈现网页

php - Laravel/PHP MySQL使用Json一对多关系

c# - 如何检查mysql中是否存在多个表?