Home  >  Article  >  Backend Development  >  How to convert JSON string to PHP object array

How to convert JSON string to PHP object array

PHPz
PHPzOriginal
2023-04-25 09:01:13549browse

With the popularity of web applications, JSON (JavaScript Object Notation) has become a popular data exchange format. In PHP, there are many ways to convert JSON data from string to PHP array or object. This article will explain how to convert a JSON string into an array of PHP objects.

Use the json_decode() function

The json_decode() function in PHP can convert a JSON string into a PHP array or object. If we want to convert a JSON string to an array of PHP objects, we just need to set the second parameter to true when calling json_decode().

Sample code:

$json_string = '{"name":"Tom", "age":28, "email":"tom@example.com"}';

// 将JSON字符串转换为PHP对象数组
$data = json_decode($json_string, true);

// 输出数组
var_dump($data);

Output result:

array(3) {
  ["name"]=>
  string(3) "Tom"
  ["age"]=>
  int(28)
  ["email"]=>
  string(15) "tom@example.com"
}

As you can see, the json_decode() function converts the JSON string into an array of PHP objects, and the $data array contains name , age and email three key-value pairs.

There are several points to note when using the json_decode() function:

  1. If the JSON string cannot be parsed, the json_decode() function will return null.
  2. If the second parameter is set to true, the json_decode() function will return an array of PHP objects, otherwise it will return a PHP object.

Summary

Using the json_decode() function, we can easily convert JSON strings into PHP arrays or objects. If we want to get an array of PHP objects, we only need to set the second parameter to true when calling json_decode(). In practical applications, we can first convert the JSON data received from the client into an array of PHP objects, and then process the array.

The above is the detailed content of How to convert JSON string to PHP object array. 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