[英]PHP - assigning variable in a foreach loop
我有一個像這樣的變量
$profile = $adapter->getProfile();
現在我這樣使用它
$profile->profileurl
$profile->websiteurl
$profile->etc
現在我想在foreach循環中使用它
所以我創建了一個像這樣的數組
$data = array('profileurl','websiteurl','etc');
foreach ($data as $d ) {
${$d} = ${'profile->'.$d};
}
當我使用var_dump(${$d})
我只會看到NULL
而不是值。
怎么了?
如下代碼:
${'profile->'.$d}
應更改為:
$profile->{$d};
這將按預期創建變量:
$profile = new stdClass();
$profile->profileurl = "test profileurl";
$profile->websiteurl = "test websiteurl";
$data = array('profileurl', 'websiteurl');
foreach ($data as $d) {
${$d} = $profile->{$d};
}
var_dump($profileurl, $websiteurl);
// string(15) "test profileurl"
// string(15) "test websiteurl"
我的猜測是$profile = $adapter->getProfile();
返回一個對象。 並且您已經使用mysql_fetch_object()
獲取了數據,因此生成的$profile
是一個對象
在數組中添加屬性時,您將必須執行以下操作
$data = array($profile->profileurl, $profile->websiteurl, $profile->etc);
這將殺死這樣做的整個想法。 因此,我建議最好嘗試修改$adapter->getProfile()
方法以使用mysql_fetch_assoc()
返回數組,該數組將返回並進行數組設置,您可以使用進行迭代
foreach($profile as $key => $value){
//whatever you want to do
echo $key . " : " . $value . "<br/>";
}
我不知道你為什么要去學習。 我的假設是,您需要像$ profileurl =“ something1”,$ websiteurl =“ something2”之類的變量。
$profile = $adapter->getProfile();
現在只需將$ profile對象轉換為Array,如下所示:
$profileArray = (array)$profile
然后使用提取功能,
extract($profileArray);
現在你得到變量的值
$profileurl = "something1";
$websiteurl="something2"
然后,您可以將其用作普通的php變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.