Home > Backend Development > PHP Tutorial > How to get the value in json in php

How to get the value in json in php

王林
Release: 2024-03-01 20:50:01
forward
819 people have browsed it

php editor Strawberry introduces you how to get the value in JSON in PHP. JSON is a lightweight data exchange format commonly used for front-end and back-end data transmission. In PHP, you can use the json_decode() function to convert a JSON string into a PHP object or array, and then access the corresponding value through object properties or array indexes. Next, we will explain in detail how to use the json_decode() function and corresponding syntax rules to obtain the value in JSON, allowing you to easily meet your data processing needs.

The following is a sample code to get the value in JSON:

$json = '{"name":"John", "age":30, "city":"New York"}';
$data = json_decode($json);

// 访问对象属性
$name = $data->name;
$age = $data->age;
$city = $data->city;

// 输出结果
echo "Name: $name, Age: $age, City: $city";

// 或者使用数组
$json = '{"name":"John", "age":30, "city":"New York"}';
$data = json_decode($json, true); // 将JSON解码为关联数组

// 访问数组元素
$name = $data['name'];
$age = $data['age'];
$city = $data['city'];

// 输出结果
echo "Name: $name, Age: $age, City: $city";
Copy after login

The above code will output:

Name: John, Age: 30, City: New York
Copy after login

Please note that the second parameter of the json_decode() function is used to specify the return value type. If set to true, an associative array is returned; if set to false or no parameters are provided, an object is returned.

The above is the detailed content of How to get the value in json in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:lsjlt.com
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