在 PHP 中,可以使用 json_decode() 函数将 JSON 字符串解码为 PHP 对象或数组,然后通过对象或数组的方式获取 JSON 对象的属性值。
- 首先,使用 json_decode() 函数将 JSON 字符串解码为 PHP 对象或数组,例如:
$json_str = "{"name":"John", "age":30, "city":"New York"}";
$json_obj = json_decode($json_str);
- 然后,可以通过对象或数组的方式获取 JSON 对象的属性值,例如:
// 通过对象的方式获取属性值
$name = $json_obj->name;
$age = $json_obj->age;
$city = $json_obj->city;
// 通过数组的方式获取属性值
$name = $json_obj["name"];
$age = $json_obj["age"];
$city = $json_obj["city"];
3. 最后,可以将获取到的属性值用于需要返回 JSON 对象的地方,例如:
// 返回 JSON 对象
echo json_encode(array(
"name" => $name,
"age" => $age,
"city" => $city
));