对象集合
我正在创建一个类,需要为我提供 MySQL 表“内容”中的所有数据。
我想让我的数据作为对象返回。 到目前为止,我设法返回一个对象,但我想获得一个对象集合,其中包含返回的数据库中的所有行。
<?
class ContentItem {
public $id;
public $title;
public $subtitle;
public $conent;
public $intro_length;
public $active;
public $start_date;
public $end_date;
public $views;
static function getContentItems() {
$query = "SELECT * FROM content";
$result = mysql_query($query)or die(mysql_error());
$item = new ContentItem();
while ($data = mysql_fetch_object($result)) {
$item = $data;
}
return $item;
}
}
I'm making a class which needs to provide me with all the data from the MySQL-table "content".
I want to have my data returned as an object.
So far I managed to get one object returned, but i'd like to get an Object Collection with all my rows from the database returned.
<?
class ContentItem {
public $id;
public $title;
public $subtitle;
public $conent;
public $intro_length;
public $active;
public $start_date;
public $end_date;
public $views;
static function getContentItems() {
$query = "SELECT * FROM content";
$result = mysql_query($query)or die(mysql_error());
$item = new ContentItem();
while ($data = mysql_fetch_object($result)) {
$item = $data;
}
return $item;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于集合,您需要创建一个实现迭代器接口的对象。你可以用数组、对象或任何你想要的东西来填充它。
Iterator
确保您可以在之后的foreach
循环中使用此集合。此外,您的代码中存在错误。您正在一遍又一遍地覆盖
$item
。您应该创建一个数组(或实现了Iterator
的对象,正如我提到的),该数组将在每个 while 循环中填充(如 tandu 已经写过)。For collections you need to create an object which implements Iterator interface. You can fill it with arrays, objects or whatever you want.
Iterator
makes sure you can use this collection inforeach
loops after.Furthermore, there's a mistake in your code. You are overwriting
$item
over and over again. You should create an array (or object with implementedIterator
, as I mentioned) which will be filled each cycle of while (as tandu wrote already).您的循环不断用
item
覆盖data
,并且new ContentItem()
会立即被覆盖。如果“对象集合”指的是“数组”,那么这很简单:如果您想返回自己的自定义对象集合,则定义集合类并每次将 $data 添加到其集合中(也可能存储在数组中) 。
Your loop keeps overwriting
data
withitem
, andnew ContentItem()
is overwritten immediately. If by "object collection" you mean "array," it's quite simple:If you want to return your own custom object collection, then define the collection class and add $data to its collection each time (probably stored in an array as well).
简单的解决方案是一个数组。我还假设您想要由每组 $data 组成的 ContentItem
如果您稍后想要使用这些项目,您可以使用 foreach
The simple solution would be an array. I also assume you want a ContentItem made from each set of $data
If you later want to work with the items, you can use foreach