PHP构造JSon数据的两种方法

PHP构造JSon数据的方式有两种,下面我就用慕课网的一个例子来用这两个方法都构造一下。

我们需要构造出如下的JSon数据:

{

    "result": 1,

    "personData": [

        {

            "name": "nate",

            "age": 12,

            "url": "http://e.hiphotos.baidu.com/zhidao/pic/item/fcfaaf51f3deb48fa05af774f31f3a292df5786c.jpg",

            "schoolInfo": [

                {

                    "school_name": "清华"

                },

                {

                    "school_name": "北大"

                }

            ]

        },

        {

            "name": "jack",

            "age": 20,

            "url": "http://e.hiphotos.baidu.com/zhidao/pic/item/fcfaaf51f3deb48fa05af774f31f3a292df5786c.jpg",

            "schoolInfo": [

                {

                    "school_name": "清华"

                },

                {

                    "school_name": "北大"

                }

            ]

        }

    ]

}



这两种方法如下:

1.使用数组array的方法构造:




这种方法虽然代码量比较小,但是看起来很乱,没有结构可言。

2.使用对象分装之后再转换成JSon

result = $result;

}

public function getResult() {

return $this->result;

}

 

public function setPersonData($personData) {

$this->personData = $personData;

}

 

public function getPersonData() {

return $this->personData;

}

}

class PersonData {

public $name;

public $age;

public $url;

public $schoolInfo;

 

public function setName($name) {

$this->name=$name;

}

 

public function getName() {

return $this->name;

}

 

public function setAge($age) {

$this->age = $age;

}

 

public function getAge() {

return $this->age;

}

 

public function setUrl($url) {

$this->url = $url;

}

 

public function getUrl() {

return $this->url;

}

 

public function setSchoolInfo($schoolInfo) {

$this->schoolInfo = $schoolInfo;

}

 

}

 

class SchoolInfo {

public $school_name;

public function __construct($school_name) {

$this->school_name = $school_name;

}

}

$schoolInfo = array();

$schoolInfo[0] = new SchoolInfo("清华");

$schoolInfo[1] = new SchoolInfo("北大");

$res = new Result();

$res->setResult(1);

$personData1 = new PersonData();

$personData1->setName("nate");

$personData1->setAge(12);

$personData1->setUrl("http://e.hiphotos.baidu.com/zhidao/pic/item/fcfaaf51f3deb48fa05af774f31f3a292df5786c.jpg");

$personData1->setSchoolInfo($schoolInfo);

 

$personData2 = new PersonData();

$personData2->setName("jack");

$personData2->setAge(20);

$personData2->setUrl("http://e.hiphotos.baidu.com/zhidao/pic/item/fcfaaf51f3deb48fa05af774f31f3a292df5786c.jpg");

$personData2->setSchoolInfo($schoolInfo);

$personData = array();

$personData[0] = $personData1;

$personData[1] = $personData2;

$res->setPersonData($personData);

$objJSon = json_encode($res);

echo $objJSon;

//print_r($res);

?>


这种方法虽然代码量比较大(因 为要创建类~~),但是看起来结构清晰了很多,这里要注意的是,JSon只能自动获取公共的数据,也就是public修饰的数据域,所以其实没必要为每个 数据域设置get方法和set方法,上面我设置了这些方法是因为开始的时候不知道,结果输出结果是空的时候我才发现,所以这里就没有删掉,留下来做个笔 记~

 

 

你可能感兴趣的:(php)