Home  >  Article  >  Backend Development  >  How to quickly convert JSON objects to arrays or object arrays in php

How to quickly convert JSON objects to arrays or object arrays in php

PHPz
PHPzOriginal
2023-04-27 16:38:11557browse

With the continuous development of Internet technology, data interaction has become an important part of Internet application development. In Web development, "data interaction" is particularly important. Data format conversion is also frequently used in web application development.

In data interaction, JSON is a very popular data format through which data objects or arrays can be passed to websites or applications. PHP is a strongly typed interpreted scripting language. Compared with other languages, PHP is more convenient to parse and use JSON format. In PHP development, it is also a very common requirement to convert a JSON-formatted string into an array or object. Then this article will introduce how to quickly convert JSON objects into arrays or object arrays.

What is JSON format?

JSON is the abbreviation of JavaScript Object Notation, which is a lightweight data exchange format. JSON is a language for exchanging data. It is a structure of key-value pairs that uses human-readable text to transmit data.

The following is a simple JSON example.

{
  "name": "bob",
  "age": 25,
  "address": {
    "city": "beijing",
    "province": "BJ"
  }
}

The data in JSON format is enclosed by curly braces, and the data exists in the form of key-value pairs, separated by colons. For a JSON object, its key must be a string, with key-value pairs separated by commas. In the above example, name, age and address are three keys, and the corresponding values ​​are "bob",# respectively. ##25 and another JSON object.

Parsing JSON format in PHP

PHP provides two built-in functions for parsing JSON strings:

json_encode() and json_decode().

  • json_encode(): Convert PHP array or object to JSON string.
  • json_decode(): Convert a JSON format string into a PHP array or object.
The following example shows how to use

json_encode() to convert a PHP array into a JSON format string.

$myArr = array('name' => 'Bob', 'age' => 25, 'address' => array('city' => 'beijing', 'province' => 'BJ'));
$jsonStr = json_encode($myArr);

echo $jsonStr; // 输出 {"name":"Bob","age":25,"address":{"city":"beijing","province":"BJ"}}
Similarly, we can use the

json_decode() function to convert a JSON format string into a PHP array.

$jsonStr = '{"name":"Bob","age":25,"address":{"city":"beijing","province":"BJ"}}';
$myArr = json_decode($jsonStr, true);

print_r($myArr); // Array ( [name] => Bob [age] => 25 [address] => Array ( [city] => beijing [province] => BJ ) )
It can be found that the return value of the

json_decode() function is a PHP array. If you want a PHP object, you can omit the second parameter, and the PHP object will be returned. As shown below:

$jsonStr = '{"name":"Bob","age":25,"address":{"city":"beijing","province":"BJ"}}';
$myObj = json_decode($jsonStr);

echo $myObj->name; // 输出 Bob
echo $myObj->address->province; // 输出 BJ
Next, this article will introduce how to convert a JSON object into a PHP array or object array.

Convert JSON object to array

We have already introduced how to convert a JSON formatted string into a PHP array. But sometimes we will pass in a JSON object from the outside and need to convert it into a PHP array for more convenient processing. Here are some common ways to convert JSON objects into PHP arrays.

1. Use

json_decode()

Use

json_decode() function can also solve this problem, but you need to pass in the second parameter.

$jsonStr = '{ "name": "bob", "age": 25, "address": { "city": "beijing", "province": "BJ" } }';
$jsonObj = json_decode($jsonStr, true);

print_r($jsonObj);
Output result:

Array
(
    [name] => bob
    [age] => 25
    [address] => Array
        (
            [city] => beijing
            [province] => BJ
        )

)
In this example, the second parameter of the

json_decode() function is set to true, which means that JSON The object is converted into a PHP array.

2. Use forced type conversion

There is a method of forced type conversion in PHP: forcing an object into an array. Using this method, a JSON object can be quickly converted into a PHP array.

$jsonStr = '{ "name": "bob", "age": 25, "address": { "city": "beijing", "province": "BJ" } }';
$jsonObj = json_decode($jsonStr);
$jsonArr = (array)$jsonObj;

print_r($jsonArr);
Output result:

Array
(
    [name] => bob
    [age] => 25
    [address] => stdClass Object
        (
            [city] => beijing
            [province] => BJ
        )

)
It should be noted that when using forced type conversion, you need to pay attention to convert the

stdClass object in the output result into a PHP array. At this time, the problem can be solved using loop recursion. In order to avoid this problem, it is generally recommended to use the json_decode() function to convert the JSON object into a PHP array.

Convert JSON object to object array

We can also convert JSON object to PHP object array. In PHP development, it is actually more common to convert a JSON array into an array of PHP objects. Here are two common ways to convert JSON objects into object arrays.

1. Use

json_decode()

You can convert JSON objects into PHP object arrays through

json_decode() and loop recursion.

$jsonStr = '{ "name": "Bob", "age": 25, "address": {"city": "beijing", "province": "BJ"} }';
$jsonObj = json_decode($jsonStr);
$objArr = array();

foreach ($jsonObj as $key => $value) {
    if (is_object($value)) {
        $objArr[$key] = $this->getJSONObj($value);
    } else if (is_array($value)) {
        $arr = array();
        foreach ($value as $item) {
            if (is_object($item)) {
                array_push($arr, $this->getJSONObj($item));
            } else {
                array_push($arr, $item);
            }
        }
        $objArr[$key] = $arr;
    } else {
        $objArr[$key] = $value;
    }
}

var_dump($objArr);
The

getJSONObj() function here converts the JSON object into an array of PHP objects and returns it.

2. Use array_map() function

In addition to the loop recursion method, we can also use the

array_map() function and anonymous function to convert JSON objects into PHP objects Array, the code is as follows:

$jsonStr = '{ "name": "Bob", "age": 25, "address": {"city": "beijing", "province": "BJ"} }';
$jsonObj = json_decode($jsonStr);

$objArr = (array)$jsonObj;
$objArr = array_map(function ($item) {
    if (is_object($item)) {
        return $this->getJSONObj($item);
    } elseif (is_array($item)) {
        return array_map(function ($sub_item) {
            return (is_object($sub_item)) ? $this->getJSONObj($sub_item) : $sub_item;
        }, $item);
    } else {
        return $item;
    }
}, $objArr);
var_dump($objArr);
The above are two common ways to convert JSON objects into object arrays. Each method can be used flexibly according to your own needs.

Summary

This article introduces how to convert JSON format data into a PHP array or object array. For conversion between JSON format and arrays in PHP development, the

json_encode() and json_decode() functions are very useful tools. There are many methods to choose from to convert JSON objects into PHP arrays or object arrays. Readers can choose the most appropriate method for implementation based on actual development needs.

The above is the detailed content of How to quickly convert JSON objects to arrays or object arrays in php. 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