2016-02-12 183 views
2

如何使用變量作爲新屬性爲對象提供新屬性?從另一個對象分配一個對象屬性

下給我所需要的屬性對象:

switch ($property['property_type']): 
    case 'Residential': 
     $property = $this->property 
         ->join('residential', 'property.id', '=','residential.property_id') 
         ->join('vetting', 'property.id', '=', 'vetting.property_id') 
         ->where('property.id', $id) 
         ->first(); 

     $property['id'] = $id; 
     break; 
    default: 
     return Redirect::route('property.index'); 
     break; 
endswitch; 

下面給我的屬性和值的列表:

$numeric_features = App::make('AttributesController')->getAttributesByType(2); 

這裏的問題是,如何動態地添加各$numeric_features屬性對象?

foreach ($numeric_features as $numeric_feature) { 
    ***$this->property->{{$numeric_feature->name}}***=$numeric_feature->value; 
} 
+1

'$ property ['id'] = $ id;'這是一個數組嗎?以及'$ numeric_features'如何組織?鍵值對象?陣列? – Webinan

+0

@ Webinan不,它們都是對象,它們都具有雄辯的db查詢的結果。 –

回答

1

看看http://php.net/manual/en/function.get-object-vars.php

$property_names = array_keys(get_object_vars($numeric_features)); 

foreach ($property_names as $property_name) { 
    $property->{$property_name} = $numeric_features->{$property_name}; 
} 

,並檢查該EVAL結果,它增加了一個對象的屬性到另一個對象: https://eval.in/517743

$numeric_features = new StdClass; 
$numeric_features->a = 11; 
$numeric_features->b = 12; 

$property = new StdClass; 
$property->c = 13; 

$property_names = array_keys(get_object_vars($numeric_features)); 

foreach ($property_names as $property_name) { 
    $property->{$property_name} = $numeric_features->{$property_name}; 
} 
var_dump($property); 

結果:

object(stdClass)#2 (3) { 
    ["c"]=> 
    int(13) 
    ["a"]=> 
    int(11) 
    ["b"]=> 
    int(12) 
} 
+0

完美,正是我所期待的。 –

相關問題