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