iT邦幫忙

0

PHP 迴圈產生變數物件成員

php

目前有一個DB的資料表,他的資料欄位,欄位是photo , photo_1,photo_2,photo_3 ...
取值得時候是用以下的方式,

<?php
foreach($result as $resultVale)
{
    echo "<img sre=".$resultValue->photo."/>";
    // 用$resultValue->photo  從物件當中取得photo值
}
?>

因為現在有photo ~photo_n 的欄位數量,
請問是否可以再
$resultValue->photo 加入變數名稱來顯示呢?

嘗試了幾種做法都是不行的,想請問是否有這種作法呢

<?php
foreach($result as $resultVale)
{
    for($i=0;$i<=5;$i++)
    {
    //顯示錯誤訊息 Undefined property: stdClass::$photo1
    //echo "<img sre=".$resultValue->{'photo'.$i}."/>"; 
    }

}
?>
img sre <=== e?
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
最佳解答

這樣…

<?php
foreach($result as $resultVale)
{
    for($i=0;$i<=5;$i++)
    {
        //顯示錯誤訊息 Undefined property: stdClass::$photo1
        $photo = 'photo_'.$i;
        //echo "<img sre=".$resultValue->{$photo}."/>"; 
    }
}
?>

舉例:

$foo = "Hello, world!";
$bar = "foo";
echo ${$bar}; // outputs "Hello, world!"
看更多先前的回應...收起先前的回應...

用上面寫法的話,
比如原本的
$resultValue->photo_1

應該不等於
$photo = 'photo'.$i;
$resultValue->${$photo}
//
$resultValue->$photo_1

這兩個應該是不同的意思?
$resultValue->$photo_1 VS $resultValue->photo_1

喔喔等等我懂了

$photo = 'photo_'.$i;
$resultValue->{$photo}

嘗試了這樣子的情況,可以了~

少加了底線,已調整
//物件的原屬性名為photo_1
$resultValue->photo_1

//物件的屬性名,根據$photo_1變數的值決定,如$photo_1 = 'test',實際屬性名為$resultValue->test
$resultValue->$photo_1

應該$resultValue->${photo} 這樣也可以吧

1.$resultValue->${photo}
這樣會跳出錯誤
Use of undefined constant photo - assumed 'photo'

2.$resultValue->{$photo}
這樣子的情況下就是正常的

太少用,一時間搞錯了,另外不加括號也是可以的~
$resultValue->$photo
/images/emoticon/emoticon06.gif

我要發表回答

立即登入回答