ooPHP - 如何从关联数组创建对象数组?
我不确定在尝试了几个小时后这是否可能,但这里...
我有一个类,UserPicture,它具有文件名、文件类型、创建等属性(即它不存储实际图片作为 blob,而是使用 $filename.$filetype 来引用它。
我希望能够有一个页面显示用户的所有图片,因此我需要从数据库中检索与该用户相关的所有行。我已经成功地将关联数组从数据库中取出,并使用以下代码来创建对象,该对象的工作原理是我通过回显它来测试它的输出...
$result=query("SELECT * FROM pictures WHERE user_id=$user_id");
// Returns associative array with numerous succesfully.
$pictures = array();
foreach($result as $row) {
$pictures = new UserPicture($row);
}
这有点工作,但我只得到最后一行数组中的一个对象。所以我尝试过 array_push...
foreach($result as $row) {
array_push($pictures, new UserPicture($row));
}
...并且我尝试使用 $pictures[]=new UserPicture($row) ,但两者都给了我以下错误...
可捕获的致命错误:类 UserPicture 的对象无法转换为 user_picture_manage.php 第 72 行中的字符串
如果有人可以请阐明我做错了什么,这将非常有帮助!
非常感谢, 史蒂夫
I'm not sure if this is even possible after trying to figure it out for hours but here goes...
I have an class, UserPicture, which has properties for filename, filetype, created etc. (i.e. it doesn't store the actual picture as a blob, rather references it by using $filename.$filetype).
I want to be able to have a page that displays all of a user's pictures, so I need to retrieve all rows from the DB relevant to that user. I've got the associative array out of the DB successfully and have used the following code to create the object, which works as I have tested the output of it by echoing it...
$result=query("SELECT * FROM pictures WHERE user_id=$user_id");
// Returns associative array with numerous succesfully.
$pictures = array();
foreach($result as $row) {
$pictures = new UserPicture($row);
}
This kinda works but I only get the last row as an object in the array. So I have tried array_push...
foreach($result as $row) {
array_push($pictures, new UserPicture($row));
}
...and I've tried using $pictures[]=new UserPicture($row), but both just give me the following error...
Catchable fatal error: Object of class UserPicture could not be converted to string in user_picture_manage.php on line 72
If anyone could please shed any light on what I'm doing wrong that would be very helpful!
Many thanks,
Steve
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您将覆盖上述代码中的
$pictures
变量。您需要为每一行添加一个新键。以下应该可以解决问题:请注意我添加方括号(
[]
)的位置。对于foreach
循环中的每次迭代,都会将一个新键添加到包含新UserPicture
类作为值的$pictures
数组中。然后,您应该能够迭代新的
$pictures
数组,如下所示:You're overwriting the
$pictures
variable in your above code. You need to add a new key for each row. The following should do the trick:Note where I've added squared braces (
[]
). For each iteration in theforeach
loop, a new key will be added to the$pictures
array containing the newUserPicture
class as the value.You should then be able to iterate over your new
$pictures
array as follows: