Home  >  Article  >  Backend Development  >  How to convert json to array in php

How to convert json to array in php

藏色散人
藏色散人Original
2022-01-20 11:36:189234browse

php method to convert json to array: 1. Create a PHP sample file; 2. Define a JSON data; 3. Convert json to an array through the "json_decode($json,true)" method.

How to convert json to array in php

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

How does php implement json to array?

json_decode()

This function is used to convert json text into the corresponding PHP data structure.

The following is an example:

$json ='{"foo": 12345}';
 
$obj = json_decode($json);
 
print $obj->{'foo'};// 12345

Normally, json_decode() always returns a PHP object, not an array. For example:

$json ='{"a":1,"b":2,"c":3,"d":4,"e":5}';
 
var_dump(json_decode($json));

The result is to generate a PHP object:

object(stdClass)#1 (5) {
 
  ["a"] => int(1)
  ["b"] => int(2)
  ["c"] => int(3)
  ["d"] => int(4)
  ["e"] => int(5)
 
}

If you want to force the generation of a PHP associative array, json_decode() needs to add a parameter true:

$json ='{"a":1,"b":2,"c":3,"d":4,"e":5}';
  
var_dump(json_decode($json,true));

The result is An associative array is generated:

array(5) {
 
   ["a"] => int(1)
   ["b"] => int(2)
   ["c"] => int(3)
   ["d"] => int(4)
   ["e"] => int(5)
}

The following three ways of writing json are all wrong. Can you see where the error is?

Common mistakes in json_decode()

$bad_json ="{ 'bar': 'baz' }";
 
$bad_json ='{ bar: "baz" }';
 
$bad_json ='{ "bar": "baz", }';

The first mistake is that the json delimiter (delimiter) only allows the use of double quotes, not single quotes. The second mistake is that the "name" (the part to the left of the colon) of the json name-value pair must use double quotes in any case. The third error is that you cannot add a trailing comma after the last value. Executing json_decode() on these three strings will return null and report an error.

In addition, json can only be used to represent objects and arrays. If json_decode() is used on a string or value, null will be returned.

var_dump(json_decode("Hello World"));//null

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to convert json to array 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