如何从 JSON PHP 中正确获取值?


若要从 JSON 中获取一个值,可以使用 json_decode()。假设我们的 JSON 如下:

$detailsJsonObject = '{"details":[{"name":"John","subjectDetails":{"subjectId":"101","subjectName":"PHP","marks":"58", "teacherName":"Bob"}}]}';  

我们需要获取具体的值,例如科目名称、分数等。

示例

PHP 代码如下:

 演示

<!DOCTYPE html>
<html>
<body>
<?php
$detailsJsonObject = '{"details":[
   {"name":"John","subjectDetails":
   {"subjectId":"101","subjectName":"PHP","marks":"58",
   "teacherName":"Bob"}
}]}';  
$convertToArrayObject = json_decode($detailsJsonObject,true);
$actualSubjectName = $convertToArrayObject[details][0][subjectDetails][subjectName];
$actualTeacherName = $convertToArrayObject[details][0][subjectDetails][teacherName];
echo "The Subject Name is=",$actualSubjectName,"<br>";
echo "The Teacher Name is=",$actualTeacherName;
?>
</body>
</html>

输出

这将产生以下输出

The Subject Name is=PHP
The Teacher Name is=Bob

更新于:2020-10-13

3K+ 浏览

开启您的 事业

完成课程即可获得认证

立即开始
广告