How to correctly get a value from a JSON PHP?


To get a value from JSON, use json_decode(). Let’s say the following is our JSON 

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

We need to fetch specific values i.e. Subject Name, Marks, etc.

Example

The PHP code is as follows 

 Live Demo

<!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>

Output

This will produce the following output

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

Updated on: 13-Oct-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements