ooPHP-如何从关联数组创建对象数组? [英] ooPHP - How do I create an array of objects from an associative array?

查看:80
本文介绍了ooPHP-如何从关联数组创建对象数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定经过数小时的尝试后是否仍然可以实现,但是这里...

I'm not sure if this is even possible after trying to figure it out for hours but here goes...

我有一个类UserPicture,它具有文件名,文件类型,创建的属性等.(即,它不将实际图片存储为Blob,而是使用$ filename.$ filetype对其进行引用).

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);
}

这有点用,但是我只将最后一行作为数组中的对象.所以我尝试了array_push ...

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));
}

...并且我尝试使用$ pictures [] = new UserPicture($ row),但是两者都给了我以下错误...

...and I've tried using $pictures[]=new UserPicture($row), but both just give me the following error...

可捕获的致命错误:在第72行的user_picture_manage.php中,类UserPicture的对象无法转换为字符串

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!

非常感谢, 史蒂夫

推荐答案

您正在覆盖以上代码中的$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:

$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);
}

请注意我在其中添加了方括号([]).对于foreach循环中的每次迭代,都会将一个新键添加到包含新UserPicture类作为值的$pictures数组中.

Note where I've added squared braces ([]). For each iteration in the foreach loop, a new key will be added to the $pictures array containing the new UserPicture class as the value.

然后,您应该可以如下遍历新的$pictures数组:

You should then be able to iterate over your new $pictures array as follows:

foreach ($pictures as $picture) {
    $src = $picture->filename . "." . $picture->filetype;
    echo '<img src="<?php echo $src; ?>" alt="" />';
}

这篇关于ooPHP-如何从关联数组创建对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆