Home > Backend Development > PHP Problem > Let's talk about how to convert json data into php array or object

Let's talk about how to convert json data into php array or object

PHPz
Release: 2023-04-17 15:56:25
Original
648 people have browsed it

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"
   }
}
Copy after login

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);
Copy after login

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
        )

)
Copy after login

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);
Copy after login

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
        )

)
Copy after login

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}
   ]
}
Copy after login

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);
Copy after login

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
                )

        )

)
Copy after login

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
                )

        )

)
Copy after login

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
   }
}
Copy after login

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);
Copy after login

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
        )

)
Copy after login

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);
Copy after login

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
   }
}
Copy after login

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);
Copy after login

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!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template