


JSON format is a lightweight data exchange format. Due to its advantages of simplicity, ease of use, speed and efficiency, it has become a widely used data format. In PHP, we can use the json_decode() function to convert a JSON string into a PHP array or object. This article will introduce how to convert JSON formatted data into PHP arrays or objects, and also explore how to handle arrays and objects in JSON.
1. Convert JSON string to PHP array
The following is an example of JSON data:
{ "name": "Tom", "age": 26, "email": "tom@example.com", "hobbies": ["reading", "swimming", "traveling"], "address": { "city": "Beijing", "province": "Beijing", "country": "China" } }
We can use the json_decode() function to convert it to a PHP array :
$json = '{ "name": "Tom", "age": 26, "email": "tom@example.com", "hobbies": ["reading", "swimming", "traveling"], "address": { "city": "Beijing", "province": "Beijing", "country": "China" } }'; $array = json_decode($json, true);
When calling the json_decode() function, the first parameter is passed in the JSON string to be converted, and the second parameter is passed in a Boolean value to specify the converted Whether the object is an array (true) or an object (false), because by default the json_decode() function converts a JSON string to an object.
We set the second parameter to true, then the return value is a PHP array, and the result is as follows:
Array ( [name] => Tom [age] => 26 [email] => tom@example.com [hobbies] => Array ( [0] => reading [1] => swimming [2] => traveling ) [address] => Array ( [city] => Beijing [province] => Beijing [country] => China ) )
2. Convert the JSON string to a PHP object
If the second parameter of the json_decode() function is set to false, a PHP object is returned. The following is a sample code:
$json = '{ "name": "Tom", "age": 26, "email": "tom@example.com", "hobbies": ["reading", "swimming", "traveling"], "address": { "city": "Beijing", "province": "Beijing", "country": "China" } }'; $obj = json_decode($json, false);
After setting the second parameter to false, $obj is a PHP object, and the result is as follows:
stdClass Object ( [name] => Tom [age] => 26 [email] => tom@example.com [hobbies] => Array ( [0] => reading [1] => swimming [2] => traveling ) [address] => stdClass Object ( [city] => Beijing [province] => Beijing [country] => China ) )
3. Processing arrays in JSON
When the JSON data contains an array, we can still use the json_decode() function to convert it to a PHP array or object. The following is an example of JSON data containing an array:
{ "name": "Tom", "age": 26, "email": "tom@example.com", "hobbies": ["reading", "swimming", "traveling"], "scores": [ {"subject": "math", "score": 90}, {"subject": "physics", "score": 85}, {"subject": "chemistry", "score": 78} ] }
We can use the json_decode() function to convert it to a PHP array:
$json = '{ "name": "Tom", "age": 26, "email": "tom@example.com", "hobbies": ["reading", "swimming", "traveling"], "scores": [ {"subject": "math", "score": 90}, {"subject": "physics", "score": 85}, {"subject": "chemistry", "score": 78} ] }'; $array = json_decode($json, true);
The converted result is as follows:
Array ( [name] => Tom [age] => 26 [email] => tom@example.com [hobbies] => Array ( [0] => reading [1] => swimming [2] => traveling ) [scores] => Array ( [0] => Array ( [subject] => math [score] => 90 ) [1] => Array ( [subject] => physics [score] => 85 ) [2] => Array ( [subject] => chemistry [score] => 78 ) ) )
We can also set the second parameter of the json_decode() function to false to convert it into a PHP object. The converted results are as follows:
stdClass Object ( [name] => Tom [age] => 26 [email] => tom@example.com [hobbies] => Array ( [0] => reading [1] => swimming [2] => traveling ) [scores] => Array ( [0] => stdClass Object ( [subject] => math [score] => 90 ) [1] => stdClass Object ( [subject] => physics [score] => 85 ) [2] => stdClass Object ( [subject] => chemistry [score] => 78 ) ) )
4. Processing objects in JSON
When JSON data contains objects, we can also use the json_decode() function to convert it into a PHP array or object . Here is an example of JSON data containing objects:
{ "name": "Tom", "age": 26, "email": "tom@example.com", "hobbies": ["reading", "swimming", "traveling"], "address": { "city": "Beijing", "province": "Beijing", "country": "China" }, "scores": { "math": 90, "physics": 85, "chemistry": 78 } }
We can still use the json_decode() function to convert it to a PHP array or object:
$json = '{ "name": "Tom", "age": 26, "email": "tom@example.com", "hobbies": ["reading", "swimming", "traveling"], "address": { "city": "Beijing", "province": "Beijing", "country": "China" }, "scores": { "math": 90, "physics": 85, "chemistry": 78 } }'; $array = json_decode($json, true); $obj = json_decode($json, false);
Converted PHP arrays and objects respectively As follows:
Array ( [name] => Tom [age] => 26 [email] => tom@example.com [hobbies] => Array ( [0] => reading [1] => swimming [2] => traveling ) [address] => Array ( [city] => Beijing [province] => Beijing [country] => China ) [scores] => Array ( [math] => 90 [physics] => 85 [chemistry] => 78 ) ) stdClass Object ( [name] => Tom [age] => 26 [email] => tom@example.com [hobbies] => Array ( [0] => reading [1] => swimming [2] => traveling ) [address] => stdClass Object ( [city] => Beijing [province] => Beijing [country] => China ) [scores] => stdClass Object ( [math] => 90 [physics] => 85 [chemistry] => 78 ) )
5. Convert PHP arrays or objects to JSON
After completing the parsing and operation of JSON data, we may also need to convert PHP arrays or objects into JSON format. String for subsequent processing or transmission. You can use the json_encode() function to convert a PHP array or object into a JSON-formatted string. The following is a sample code:
$array = array( 'name' => 'Tom', 'age' => 26, 'email' => 'tom@example.com', 'hobbies' => array('reading', 'swimming', 'traveling'), 'address' => array( 'city' => 'Beijing', 'province' => 'Beijing', 'country' => 'China' ), 'scores' => array( 'math' => 90, 'physics' => 85, 'chemistry' => 78 ) ); $json = json_encode($array);
After calling the json_encode() function, the value of $json is the converted JSON format string, and the result is as follows:
{ "name":"Tom", "age":26, "email":"tom@example.com", "hobbies":["reading","swimming","traveling"], "address":{ "city":"Beijing", "province":"Beijing", "country":"China" }, "scores":{ "math":90, "physics":85, "chemistry":78 } }
6. Convert PHP array or object Convert to JSON and output
If you need to directly output JSON format data in PHP, we can directly output the result after calling the json_encode() function. The following example:
$array = array( 'name' => 'Tom', 'age' => 26, 'email' => 'tom@example.com', 'hobbies' => array('reading', 'swimming', 'traveling'), 'address' => array( 'city' => 'Beijing', 'province' => 'Beijing', 'country' => 'China' ), 'scores' => array( 'math' => 90, 'physics' => 85, 'chemistry' => 78 ) ); header('Content-Type: application/json'); echo json_encode($array);
In the above example, we set the response header information through the header() function and set the ContentType to application/json, indicating that the returned data is in JSON format. Then use echo to output the converted JSON data.
Conclusion
This article mainly introduces how to convert JSON data into PHP arrays or objects. It also discusses how to handle arrays and objects in JSON, and demonstrates the conversion of PHP arrays or objects. Method for a JSON-formatted string. I hope this article can help PHP developers.
The above is the detailed content of Let's talk about how to convert json data into php array or object. For more information, please follow other related articles on the PHP Chinese website!

This article explores efficient PHP array deduplication. It compares built-in functions like array_unique() with custom hashmap approaches, highlighting performance trade-offs based on array size and data type. The optimal method depends on profili

This article analyzes PHP array deduplication, highlighting performance bottlenecks of naive approaches (O(n²)). It explores efficient alternatives using array_unique() with custom functions, SplObjectStorage, and HashSet implementations, achieving

This article explores PHP array deduplication using key uniqueness. While not a direct duplicate removal method, leveraging key uniqueness allows for creating a new array with unique values by mapping values to keys, overwriting duplicates. This ap

This article details implementing message queues in PHP using RabbitMQ and Redis. It compares their architectures (AMQP vs. in-memory), features, and reliability mechanisms (confirmations, transactions, persistence). Best practices for design, error

This article examines current PHP coding standards and best practices, focusing on PSR recommendations (PSR-1, PSR-2, PSR-4, PSR-12). It emphasizes improving code readability and maintainability through consistent styling, meaningful naming, and eff

This article details installing and troubleshooting PHP extensions, focusing on PECL. It covers installation steps (finding, downloading/compiling, enabling, restarting the server), troubleshooting techniques (checking logs, verifying installation,

This article explores optimizing PHP array deduplication for large datasets. It examines techniques like array_unique(), array_flip(), SplObjectStorage, and pre-sorting, comparing their efficiency. For massive datasets, it suggests chunking, datab

This article explains PHP's Reflection API, enabling runtime inspection and manipulation of classes, methods, and properties. It details common use cases (documentation generation, ORMs, dependency injection) and cautions against performance overhea


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Linux new version
SublimeText3 Linux latest version
