我知道这可能很简单,但是我陷入了困境,无法找到解决方案。我只想创建一个简单的嵌套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]"}
}
如何创建外部“用户”部分?
你可以做 json_encode(array('user' => $up->expose());
因此,基本上,您犯的唯一错误是使用,
而不是=>
,它为您提供了一个包含两个对象的数组,而不是具有key => value的关联数组。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句