Home  >  Article  >  Backend Development  >  Convert json string to array php

Convert json string to array php

王林
王林Original
2023-05-06 13:59:091586browse

In PHP, you can use the json_decode() function to convert a JSON string into an array.

The syntax of the json_decode() function is as follows:

mixed json_decode(string $json_string, bool $assoc = false, int $depth = 512, int $options = 0)

The first parameter is the JSON string to be converted, and the second parameter is an optional Boolean type parameter, specifying whether Convert JSON objects to associative arrays instead of the default array of objects. If it is set to true, the JSON object will be converted to an associative array, otherwise the JSON object structure will be preserved. The third parameter specifies the maximum recursion depth of the JSON string, and the default value is 512. The last parameter specifies some optional parameters, such as specifying the encoding method of the JSON string, etc.

Here is an example that demonstrates how to convert a JSON string to an array:

<?php
  // 定义一个JSON字符串
  $json_string = '{"name": "Tom", "age": 30, "email": "tom@example.com"}';

  // 将JSON字符串转换为关联数组
  $assoc_array = json_decode($json_string, true);

  // 输出转换后的数组
  print_r($assoc_array);
?>

Output result:

Array
(
    [name] => Tom
    [age] => 30
    [email] => tom@example.com
)

In the above example, we convert the JSON string is an associative array, and uses the print_r() function to output the results to the screen.

It should be noted that if the JSON string is invalid or incorrectly formatted, the json_decode() function will return null. If you need to get more detailed error information, you can use the json_last_error() function to get the error code of the last JSON decoding operation.

<?php
  // 定义一个无效的JSON字符串
  $json_string = '{name: "Tom", age: 30, email: "tom@example.com"}';

  // 将JSON字符串转换为数组
  $array = json_decode($json_string, true);

  // 判断是否解码成功
  if($array === null && json_last_error() !== JSON_ERROR_NONE){
    // 输出错误信息
    echo 'json_decode failed with error code: ' . json_last_error_msg();
  }else{
    // 输出解码结果
    print_r($array);
  }
?>

Output result:

json_decode failed with error code: Syntax error

The above is the basic usage of converting JSON string to array. I believe you have mastered it.

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