2016-11-28 122 views
2

我将只声明一次数组。价值想要一次又一次地作为关键别名来调用。请任何人都可以帮助我? 例如:PHP数组变量声明为别名

我:

<?php 
$id = $profile[0]->id; 
$roll = $profile[0]->roll; 
$photo = $profile[0]->photo; 
$active = $profile[0]->active; 
?> 

我neeed:

<?php 
$var as $profile[0]; 
$id = $var->id; 
$roll = $var->roll; 
$photo = $var->photo; 
$active = $var->active; 
?> 

它可以用foreach()来完成。但是,我想在Alias上工作。 我需要什么好的想法..

回答

0

我想你可以试试这个

<?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; 
    ?> 
0
foreach($profile[0] as $key => $val) { 
    $$key = $val; 
} 
0

你可以使用list()结构用于此目的。

list($profile) = $profiles; 
$id = $profile->id; 
$roll = $profile->roll; 
$photo = $profile->photo; 
$active = $profile->active; 

可变$profile相当于$profiles[0]。所以,你可以坚持这样做。

0

我不知道你在找什么100%,但我觉得你references后,更具体地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) 

现在$var是指向同一个对象,$profile[0],你可以通过两种变量修改一个变量名:

$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) 
    } 
} 

当然,这一切都是一种矫枉过正,如果你实际上并不需要改变原来的数组,这就够了:

$var = $profile[0];