2014-01-10 93 views
-2

我知道這可能很簡單,但我卡住了,無法找到解決方案。我只是想創建一個簡單的嵌套JSON對象,看起來像以下:如何在PHP5中創建一個嵌套的json對象

{ 
    "user": {"firstname":"foo","lastname":"bar","email":"[email protected]"} 
} 

到目前爲止,我可以創建內JSON如下:

class user_profile { 
    private $firstname = ''; 
    private $lastname =''; 
    private $email = ''; 
    public function __construct($first, $last, $email){ 
     $this->firstname = $first; 
     $this->lastname = $last; 
     $this->email = $email; 
    } 
    public function expose() { 
     return get_object_vars($this); 
    } 

} 
$up = new user_profile('foo','bar','[email protected]'); 
echo json_encode($up->expose()); 

我嘗試添加一個數組:

echo json_encode(array('user',$up->expose()), JSON_FORCE_OBJECT); 

但其結果是:

{ 
    "0":"user","1": {"firstname":"foo","lastname":"bar","email":"[email protected]"} 
} 

如何創建外部「用戶」部分?

回答

1

你可以做json_encode(array('user' => $up->expose());

所以基本上你發用,代替=>唯一的失誤,這給了你兩個物體,而不是與鍵=>值的關聯數組的數組。