使用 PHP 读取 JSON 数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5868721/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read JSON Data Using PHP
提问by Aadi
Solr returns response in following JSON format.
Solr 以以下 JSON 格式返回响应。
{
"responseHeader":{
"status":0,
"QTime":2,
"params":{
"indent":"on",
"start":"0",
"q":"*:*",
"wt":"json",
"version":"2.2",
"rows":"10"}},
"response":{"numFound":3,"start":0,"docs":[
{
"student_id":"AB1001",
"student_name":[
"John"]
},
{
"student_id":"AB1002",
"student_name":[
"Joe"]
},
{
"student_id":"AB1003",
"student_name":[
"Lorem"]
}]
}}
What will be the simple way to read student_id, student_name using PHP?
使用 PHP 读取 student_id, student_name 的简单方法是什么?
回答by ThiefMaster
Use $obj = json_decode($yourJSONString);
to convert it to an object.
使用$obj = json_decode($yourJSONString);
将其转换为一个对象。
Then use foreach($obj->response->docs as $doc)
to iterate over the "docs".
然后用于foreach($obj->response->docs as $doc)
迭代“文档”。
You can then access the fields using $doc->student_id
and $doc->student_name[0]
.
然后,您可以使用$doc->student_id
和访问这些字段$doc->student_name[0]
。
回答by honeyp0t
PHP has a json_decode function that will allow you to turn a JSON string into an array:
PHP 有一个 json_decode 函数,可以将 JSON 字符串转换为数组:
$array = json_decode($json_string, true);
$student_id = $array['response']['docs'][0]['student_id'];
...
Of course, you might want to iterate through the list of students instead of accessing index 0.
当然,您可能希望遍历学生列表而不是访问索引 0。
回答by deceze
$result = json_decode($result, true);
$result['response']['docs'][0]['student_id'] ...
回答by Mauricio Scheffer
Why not just use one of the PHP clients for Solr, or the PHP response writer? See http://wiki.apache.org/solr/SolPHP
为什么不只使用 Solr 的 PHP 客户端之一或 PHP 响应编写器?见http://wiki.apache.org/solr/SolPHP
回答by user3917016
$json_a = json_decode($string, TRUE);
$json_o = json_decode($string);
#array method
foreach($json_a['response']['docs'] as $students)
{
echo $students['student_id']." name is ".$students['student_name'][0];
echo "<br>";
}
#Object Method`enter code here`
foreach($json_o->response->docs as $sthudent_o)
{
echo $sthudent_o->student_id. " name is ".$sthudent_o->student_name[0];
echo "<br>";
}