2016-03-10 165 views
0

我想創建一個具有以下圖層的php對象。如何創建嵌套的php對象

$obj->property->name; 
$obj->property->title; 
$obj->property->id; 
$obj->property->height; 

這給我 'Trying to get property of non-object' 錯誤

我的目標

$obj = [ 
    'property' => [ 
     'name' => 'Rick', 
     'title' => 'manager', 
     'id' => '123', 
     'height' => '5.6' 
    ] 
]; 

$obj = = (object)$obj; 

我不知道正確的語法產生$obj->property->name;任何人都可以幫我嗎?我的大腦被解僱了......謝謝!

+0

'$ obj'被聲明爲一個數組,你可以只投'(對象)'在聲明 – Ghost

+0

這應該是'$ obj->屬性[ '名稱'];' – devpro

回答

1

你應該投 到objectproperty

$obj = [ 
    'property' => [ 
     'name' => 'Rick', 
     'title' => 'manager', 
     'id' => '123', 
     'height' => '5.6' 
    ] 
]; 

$object = (object)$obj; 
$object->property = (object)$object->property; 

結果:

var_dump($object->property->id); // string(3) "123" 
var_dump($object->property->name); // string(4) "Rick" 
// etc. 
1

你有property object一個數組裏面,你可以不喜歡這樣

$obj->property->name; 

使用這應該是:

$obj->property['name']; 

例子:

$yourArr = array('property'=>array(
     'name' => 'Rick', 
     'title' => 'manager', 
     'id' => '123', 
     'height' => '5.6' 
    )); 

$yourObj = (object) $yourArr; 
echo $yourObj->property['name']; // Rick