I have a string which is in valid Json format and it looks like this:
{
"message": "success",
"result": {
"46620": {
"course_id": "29",
"en_title": "Google Analytics (Basic)",
"fa_title": "مبانی گوگل آنالیتیکز",
"badge_link": "http://www.darsnameh.com/badge/index.php?user=46620&badge="
},
"49449": {
"course_id": "16",
"en_title": "Multimedia Reporting 1- Reporting in the Internet Age",
"fa_title": "گزارش‌گری چندرسانه‌ای ۱- گزارشگری در زمانه‌ی اينترنت",
"badge_link": "http://www.darsnameh.com/badge/index.php?user=49449&badge="
},
"55480": {
"course_id": "33",
"en_title": "HTML for Journalists and Bloggers",
"fa_title": "آشنایی با اچ‌تی‌ام‌ال Ùˆ Ùناوری‌های اینترنت برای روزنامه‌نگاران Ùˆ وبلاگ‌نویس‌ها",
"badge_link": "http://www.darsnameh.com/badge/index.php?user=55480&badge="
},
"59250": {
"course_id": "31",
"en_title": "Twitter",
"fa_title": "توییتر",
"badge_link": "http://www.darsnameh.com/badge/index.php?user=59250&badge="
},
"103716": {
"course_id": "42",
"en_title": "How to write a CV?",
"fa_title": "چگونه رزومه بنویسیم؟",
"badge_link": "http://www.darsnameh.com/badge/index.php?user=103716&badge="
}
}
}
I want to read different fields, for example all fa_titles, I use $obj = json_decode($str, true); to convert this to Json, then echo sizeof($obj['result']); shows me that it has 5 result object, but how can I access to fa_title or en_title fields now?
In JSON, arrays are designated by brackets (
[
and]
) while dictionaries only have braces ({
and}
).You could access each result object individually by doing
$obj['result']['46620']['en_title']
. The result object is an associative array (also known as a dictionary) of associative arrays.You can also iterate through each object using a
foreach
loop, as demonstrated in this questionTo loop through all the results, something like this should do it: