Home  >  Article  >  Backend Development  >  How to convert php string to object

How to convert php string to object

藏色散人
藏色散人Original
2021-06-03 09:49:174356browse

In PHP, you can convert a string into an object through the "json_decode" function. The syntax for using this function is "json_decode ( string $json [, bool $assoc = false [, int $depth..." .

How to convert php string to object

The operating environment of this article: Windows 7 system, PHP version 7.1, DELL G3 computer

Convert the string into a php object

  • json_decode(): decoding - the string becomes an object in php

  • json_encode(): encoding - php The object becomes a string

json_decode is a PHP built-in function added after php5.2.0. Its function is to encode strings in JSON format. Then How to use this function?

The syntax rules of json_decode:

 json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )

json_decode accepts a JSON format string and converts it into a PHP variable. When the parameter $assoc is TRUE, Array will be returned, otherwise object will be returned.

JSON format string

$json = '{"a":"php","b":"mysql","c":3}';

Where a is the key, php is the key value of a.

Example:

Program output:

stdClass Object (
  [a] => php
  [b] => mysql
  [c] => 3 )
  Array (
  [a] => php
  [b] => mysql
  [c] => 3 )

Under the premise of the above code

Access the value of a of the object type $json_Class

echo $json_Class->{'a'};

Program output: php

Access the value of a in the array type $json_Array

echo $json_Array['a'];

Program output: php

Recommended learning: "PHP Video Tutorial"

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