简体   繁体   English

PHP:如何遍历具有顺序名称的属性

[英]PHP: How to loop through properties with sequential names

If I have a table with columns called image1, image2, image3, etc and I pulled those in an object-oriented manner, like this: 如果我有一个表,其中包含名为image1,image2,image3等的列,并且以面向对象的方式提取了这些列,如下所示:

$images->image1
$images->image2
$images->image3

etc. 等等

Is there any way to process these in a loop? 有什么办法可以循环处理这些吗? Something like: 就像是:

for (i=1; i<count($images); $i++) {
    $array[$i] = $images->image?
}

I realize the above won't work, but was wondering if someone could tell me a way that will work. 我意识到上述方法无效,但想知道是否有人可以告诉我可行的方法。 Thanks. 谢谢。

Pulling them from the DB in an array might be a better option, but you can do it with objects by using variable variables : 将它们从数据库中的数组中拉出可能是更好的选择,但是您可以通过使用变量variable对对象进行操作:

for ($i = 1; i < $length; $i++) {
    $array[] = $images->{'image' . $i};
}

You should use an array instead. 您应该改用数组

However, you can also use variable variables for this madder. 但是,您也可以为此变量使用变量变量

for ($i = 1; i < $len; $i++) {
    $array[] = $images->{'image' + $i};
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM