如何从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