问题描述
我有一个有效的 Json 格式的字符串,它看起来像这样:
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="
}
}
}
我想读取不同的字段,例如所有 fa_titles,我使用 $obj = json_decode($str, true);将其转换为 Json,然后 echo sizeof($obj['result']);显示它有 5 个结果对象,但我现在如何访问 fa_title 或 en_title 字段?
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?
推荐答案
在 JSON 中,数组由括号([
和 ]
)指定,而字典只有括号({
和 }
).
In JSON, arrays are designated by brackets ([
and ]
) while dictionaries only have braces ({
and }
).
您可以通过执行 $obj['result']['46620']['en_title']
来单独访问每个结果对象.结果对象是关联数组的关联数组(也称为字典).
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.
您还可以使用 foreach
循环遍历每个对象,如 这个问题
You can also iterate through each object using a foreach
loop, as demonstrated in this question
这篇关于在 PHP 中读取 Json/Array 字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!