How to convert json to array in php

藏色散人
Release: 2023-03-14 21:48:02
Original
9259 people have browsed it

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

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

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

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

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

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

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

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!

Related labels:
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