Home > Backend Development > PHP Tutorial > PHP对象转成JSON

PHP对象转成JSON

WBOY
Release: 2016-06-06 20:18:29
Original
1218 people have browsed it

先定义有个 class:

<code>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;
    }
}</code>
Copy after login
Copy after login

这样的,我想要生成的JSON格式类似于:

<code>{“info":"read the data succeed","UserBean":[{"user_id":"21","user_name":"小明"},{":[{"user_id":"23","user_name":"小东"}]}</code>
Copy after login
Copy after login

其中 UserBean下面是不确定个数的对象。。。
这样的JSON数据要怎么生成。。。?
有没有 像 JAVA 中 List'' 这样的东西。。。
求大神帮助。。。

回复内容:

先定义有个 class:

<code>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;
    }
}</code>
Copy after login
Copy after login

这样的,我想要生成的JSON格式类似于:

<code>{“info":"read the data succeed","UserBean":[{"user_id":"21","user_name":"小明"},{":[{"user_id":"23","user_name":"小东"}]}</code>
Copy after login
Copy after login

其中 UserBean下面是不确定个数的对象。。。
这样的JSON数据要怎么生成。。。?
有没有 像 JAVA 中 List'' 这样的东西。。。
求大神帮助。。。

{“info":"read the data succeed","UserBean":[{"user_id":"21","user_name":"小明"},{":[{"user_id":"23","user_name":"小东"}]}

PHP实现:先生成数组再json编码

<code>$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));</code>
Copy after login

可以直接从数据库查询UserBean结果集
也可以自己拼装数组

正解:

<code>$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);</code>
Copy after login
Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template