search
HomeBackend DevelopmentPHP ProblemHow 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.

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;
?>

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!

Statement
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor