2014-01-10 67 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());

所以基本上你发用,代替=>唯一的失误,这给了你两个物体,而不是与键=>值的关联数组的数组。