Home >Backend Development >PHP Problem >How to convert php object array to json string
How to convert php object array to json string: first create a PHP sample file; then create an array; and finally convert the array into json format through the "json_encode($array);" method.
Recommended: "PHP Video Tutorial"
PHP converts objects into json string arrays json array instance
<?php //创建数组 $array = array( "name" => "Hza", "age" => 21 ); //数组转化为json格式 echo json_encode($array); echo "<br />"; //创建类 class Student { public $name; public $age; //初始化是赋值 function __construct($name, $age) { $this->name = $name; $this->age = $age; } //魔术方法 把对象转换成字符串格式 以备使用json_encode()函数 function __tostring() { //对象转化为json格式 return json_encode($this,JSON_FORCE_OBJECT); } } //实例化对象 $person1 = new Student('Hza', 20); //输出json格式 echo $person1; ?>
The above is the detailed content of How to convert php object array to json string. For more information, please follow other related articles on the PHP Chinese website!