문제

I have a variable like this

$profile = $adapter->getProfile();

Now i'm using it like this

$profile->profileurl
$profile->websiteurl
$profile->etc

Now i want to use it in a foreach loop

So i created an array like this

$data = array('profileurl','websiteurl','etc');

foreach ($data as $d ) {
${$d} = ${'profile->'.$d};
}

When I use var_dump(${$d}) I see only NULL instead of values.

Whats wrong?

도움이 되었습니까?

해결책

The following code:

${'profile->'.$d}

Should be changed to:

$profile->{$d};

This will create the variables as expected:

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

다른 팁

My guess is that $profile = $adapter->getProfile(); returns an object. And you have fetched data using mysql_fetch_object() so the resulting $profile is an object

When you add the properties in an array you will have to do something like this

$data = array($profile->profileurl, $profile->websiteurl, $profile->etc);

Which will kill the entire idea of doing so. So i'd suggest better try modifying the $adapter->getProfile() method to return an array using mysql_fetch_assoc() which which will return and array and you can iterate it using

foreach($profile as $key => $value){
    //whatever you want to do
    echo $key .  " : " . $value . "<br/>";
}

I don't know exactly why are you approaching foreach. My assumption is, you need variable like $profileurl = "something1", $websiteurl="something2" and more.

$profile = $adapter->getProfile();

Now just convert $profile object into Array as follows,

$profileArray = (array)$profile

Then use extract function,

extract($profileArray);

Now you get values in variable as

$profileurl = "something1";
$websiteurl="something2"

Then you can use those as normal php variable.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top