I will declare an array just once. Value would like to call again and again as the key alias. please any one can help me? example:
I have :
<?php
$id = $profile[0]->id;
$roll = $profile[0]->roll;
$photo = $profile[0]->photo;
$active = $profile[0]->active;
?>
I neeed :
<?php
$var as $profile[0];
$id = $var->id;
$roll = $var->roll;
$photo = $var->photo;
$active = $var->active;
?>
It can be done with foreach () . However, I would like to work on Alias. i need any good idea..
foreach($profile[0] as $key => $val) {
$$key = $val;
}
You could use list()
construct for this purpose.
list($profile) = $profiles;
$id = $profile->id;
$roll = $profile->roll;
$photo = $profile->photo;
$active = $profile->active;
The variable $profile
is equivalent to $profiles[0]
. So, you could stick with this way of doing it.
I think you can try this
<?php
// this line you can try
$var = array();
// your code
$var = $profile[0];
$id = $var->id;
$roll = $var->roll;
$photo = $var->photo;
$active = $var->active;
?>
I'm not 100% sure of what you're looking for but I feel you're after references , more specifically to assign by reference :
$profile = array(
0 => (object)array(
'id' => '314',
'roll' => 'XYZ',
'photo' => 'foo.jpg',
'active' => true,
),
);
$var = &$profile[0];
$id = $var->id;
$roll = $var->roll;
$photo = $var->photo;
$active = $var->active;
var_dump($id, $roll, $photo, $active);
string(3) "314"
string(3) "XYZ"
string(7) "foo.jpg"
bool(true)
Now $var
is a variable name that points to the same object that $profile[0]
that you can modify it through either variables:
$var->photo = 'flowers.gif';
var_dump($profile);
array(1) {
[0]=>
&object(stdClass)#1 (4) {
["id"]=>
string(3) "314"
["roll"]=>
string(3) "XYZ"
["photo"]=>
string(11) "flowers.gif"
["active"]=>
bool(true)
}
}
Of course, all this is kind of overkill if you don't actually need to alter the original array and this would suffice:
$var = $profile[0];
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.