使用PHP读取JSON数据

Aad*_*adi 9 php json solr

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"]
    }]

  }}
Run Code Online (Sandbox Code Playgroud)

使用PHP读取student_id,student_name的简单方法是什么?

Thi*_*ter 15

使用$obj = json_decode($yourJSONString);将其转换为一个对象.

然后foreach($obj->response->docs as $doc)用来迭代"docs".

然后,您可以使用$doc->student_id和访问字段$doc->student_name[0].


小智 10

PHP有一个json_decode函数,允许您将JSON字符串转换为数组:

$array = json_decode($json_string, true);
$student_id = $array['response']['docs'][0]['student_id'];
...
Run Code Online (Sandbox Code Playgroud)

当然,您可能希望遍历学生列表而不是访问索引0.