Rumah > Soal Jawab > teks badan
先定义有个 class:
class UserBean {
public $user_id = 0;
public $user_name = 'null';
function setUser_id ($user_id) {
$this->user_id = $user_id;
}
function setUser_name ($user_name) {
$this->user_name = $user_name;
}
function getUser_id () {
return $this->user_id;
}
function getUser_name () {
return $this->user_name;
}
}
这样的,我想要生成的JSON格式类似于:
{“info":"read the data succeed","UserBean":[{"user_id":"21","user_name":"小明"},{":[{"user_id":"23","user_name":"小东"}]}
其中 UserBean下面是不确定个数的对象。。。
这样的JSON数据要怎么生成。。。?
有没有 像 JAVA 中 List'<'T'>' 这样的东西。。。
求大神帮助。。。
PHPz2017-04-10 16:49:24
{“info":"read the data succeed","UserBean":[{"user_id":"21","user_name":"小明"},{":[{"user_id":"23","user_name":"小东"}]}
PHP实现:先生成数组再json编码
$data['info'] = '';
$data['UserBean'][0]['user_id'] = '';
$data['UserBean'][0]['user_name'] = '';
$data['UserBean'][1]['user_id'] = '';
$data['UserBean'][1]['user_name'] = '';
exit(json_encode($data));
可以直接从数据库查询UserBean结果集
也可以自己拼装数组
ringa_lee2017-04-10 16:49:24
正解:
$data['info'] = 'succeed';
$data['UserBean'][0]['user_id'] = '1';
$data['UserBean'][0]['user_name'] = '小明';
$data['UserBean'][1]['user_id'] = '2';
$data['UserBean'][1]['user_name'] = '栗子';
echo json_encode($data);