How to convert php object array to json string

藏色散人
Release: 2023-03-06 17:24:02
Original
2971 people have browsed it

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.

How to convert php object array to json string

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(&#39;Hza&#39;, 20);
//输出json格式
echo $person1;
?>
Copy after login

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!

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