简体   繁体   中英

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:

$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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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