How to convert json to array in php?

青灯夜游
Release: 2023-03-03 07:26:01
Original
12687 people have browsed it

In PHP, you can use the json_decode() function to convert json format data into an array. The json_decode() function can convert a json string into an object or array. It is converted into an object by default. Specify the second parameter as a Boolean value true, so that the JSON value will be decoded into an associative array.

How to convert json to array in php?

json_decode() function is a built-in function in PHP, used to decode JSON format strings and convert JSON format strings into PHP Variable (object or array). [Related tutorial recommendations: "PHP Tutorial"]

By default, the json_decode() function will return an object; however, you can specify the second parameter to be a Boolean value true, so JSON values ​​will be decoded into associative arrays.

Basic syntax:

json_decode( $json, $assoc = FALSE, $depth = 512, $options = 0 )
Copy after login

Parameters:

  • ##json: It contains the JSON string that needs to be decoded. It only works with UTF-8 encoded strings.

  • assoc: This is a Boolean variable. If true, the returned object will be converted to an associative array.

  • depth: It represents the user-specified recursion depth.

  • options: Bitmask containing JSON_OBJECT_AS_ARRAY, JSON_BIGINT_AS_STRING, JSON_THROW_ON_ERROR.

Return value: This function returns the encoded JSON value in the appropriate PHP type. If the json cannot be decoded or the encoded data is deeper than the recursion limit, NULL is returned.

Example:

<?php
$json = &#39;{"a":1,"b":2,"c":3,"d":4,"e":5}&#39;;
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>
Copy after login

Output:

object(stdClass)[1]  public &#39;a&#39; => int 1
  public &#39;b&#39; => int 2
  public &#39;c&#39; => int 3
  public &#39;d&#39; => int 4
  public &#39;e&#39; => int 5
array (size=5)
  &#39;a&#39; => int 1
  &#39;b&#39; => int 2
  &#39;c&#39; => int 3
  &#39;d&#39; => int 4
  &#39;e&#39; => int 5
Copy after login
Recommended learning:

PHP programming from entry to master

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