Home Backend Development PHP Problem How to convert php object array into json string array

How to convert php object array into json string array

Apr 19, 2023 pm 02:11 PM

In modern web development, JavaScript-based front-end programs using JSON (JavaScript Object Notation) format data have become a regular choice. PHP is a common server-side programming language. Often we need to convert PHP objects or arrays into JSON format strings on the server side to facilitate front-end calls. In this article, we will show you how to convert an array of objects into a JSON string array in PHP.

  1. Use json_encode() function

The json_encode() function is built into PHP, which can convert PHP arrays and objects into JSON format strings, as follows Display:

<?php
$array = array(&#39;name&#39; => '张三', 'age' => 18, 'gender' => 'male');
echo json_encode($array);
?>
Copy after login

Run result:

{"name":"张三","age":18,"gender":"male"}
Copy after login

In this example we can see that when the PHP array is passed into the json_encode() function, an encoded JSON format string can be returned. Note here: the json_encode() function only supports UTF-8 encoding format. If the encoding format used by your string is not UTF-8, an error will occur. Therefore, before using the json_encode() function, please ensure that the array or object that needs to be converted has been converted to UTF-8 format.

  1. JSON formatting of object array

If you need to convert the object array into a JSON string array, you need to convert the object into an array and use the json_encode() function for processing. For example, we need to convert the object array representing student information into a JSON format string array:

<?php
class Student{
    public $name;
    public $age;
    public $gender;
}
$student1 = new Student();
$student1->name = '张三';
$student1->age = 18;
$student1->gender = 'male';

$student2 = new Student();
$student2->name = '李四';
$student2->age = 19;
$student2->gender = 'female';

$students = array();
array_push($students,$student1,$student2);

$students_arr = array();
foreach($students as $student){
    $obj = get_object_vars($student);
    array_push($students_arr,$obj);
}

echo json_encode($students_arr);
?>
Copy after login

Running result:

[{"name":"张三","age":18,"gender":"male"},{"name":"李四","age":19,"gender":"female"}]
Copy after login

In the above example, we created an array that can represent Student class for student information, and uses an array to store multiple Student objects. When converting the Student object to an array, the get_object_vars() function is used. This function converts the object into an associative array, allowing us to handle the object like an array. Finally, pass the array to the json_encode() function and output the result.

At the same time, in order to better assist understanding, we can also transform the above example into a more intuitive form, as shown in the following figure:

  1. JSON_PRETTY_PRINT option

Through the above two examples, you have learned how to convert a PHP object or array into a JSON format string array. However, at first glance these JSON formatted string arrays look a bit hard to read. In order to beautify the JSON data format, you can use the second parameter of the json_encode() function: JSON_PRETTY_PRINT selection, as shown below:

<?php
$array = array(&#39;name&#39; => '张三', 'age' => 18, 'gender' => 'male');
echo json_encode($array,JSON_PRETTY_PRINT);
?>
Copy after login

Running result:

{
    "name": "张三",
    "age": 18,
    "gender": "male"
}
Copy after login

This is what happens after using the JSON_PRETTY_PRINT option The output results are clearer and easier to read.

In this article, we introduced how to convert an array of objects into a JSON string array in PHP. This is an important step in our front-end and back-end interaction. Combined with the front-end JSON parsing tool, the data can be easily converted into the format required by each website.

The above is the detailed content of How to convert php object array into json string array. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

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.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8 JIT (Just-In-Time) Compilation: How it improves performance. PHP 8 JIT (Just-In-Time) Compilation: How it improves performance. Mar 25, 2025 am 10:37 AM

PHP 8's JIT compilation enhances performance by compiling frequently executed code into machine code, benefiting applications with heavy computations and reducing execution times.

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities. OWASP Top 10 PHP: Describe and mitigate common vulnerabilities. Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP Secure File Uploads: Preventing file-related vulnerabilities. PHP Secure File Uploads: Preventing file-related vulnerabilities. Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Encryption: Symmetric vs. asymmetric encryption. PHP Encryption: Symmetric vs. asymmetric encryption. Mar 25, 2025 pm 03:12 PM

The article discusses symmetric and asymmetric encryption in PHP, comparing their suitability, performance, and security differences. Symmetric encryption is faster and suited for bulk data, while asymmetric is used for secure key exchange.

PHP Authentication & Authorization: Secure implementation. PHP Authentication & Authorization: Secure implementation. Mar 25, 2025 pm 03:06 PM

The article discusses implementing robust authentication and authorization in PHP to prevent unauthorized access, detailing best practices and recommending security-enhancing tools.

How do you retrieve data from a database using PHP? How do you retrieve data from a database using PHP? Mar 20, 2025 pm 04:57 PM

Article discusses retrieving data from databases using PHP, covering steps, security measures, optimization techniques, and common errors with solutions.Character count: 159

PHP CSRF Protection: How to prevent CSRF attacks. PHP CSRF Protection: How to prevent CSRF attacks. Mar 25, 2025 pm 03:05 PM

The article discusses strategies to prevent CSRF attacks in PHP, including using CSRF tokens, Same-Site cookies, and proper session management.

What is the purpose of mysqli_query() and mysqli_fetch_assoc()? What is the purpose of mysqli_query() and mysqli_fetch_assoc()? Mar 20, 2025 pm 04:55 PM

The article discusses the mysqli_query() and mysqli_fetch_assoc() functions in PHP for MySQL database interactions. It explains their roles, differences, and provides a practical example of their use. The main argument focuses on the benefits of usin

See all articles