Чтение данных JSON с использованием PHP

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

Каким будет простой способ прочитать student_id, имя_сестра с помощью PHP?

Используйте $obj = json_decode($yourJSONString); чтобы преобразовать его в объект.

Затем используйте foreach($obj->response->docs as $doc) чтобы перебирать «документы».

Затем вы можете получить доступ к полям с помощью $doc->student_id и $doc->student_name[0] .

PHP имеет функцию json_decode, которая позволит вам превратить строку JSON в массив:

 $array = json_decode($json_string, true); $student_id = $array['response']['docs'][0]['student_id']; ... 

Конечно, вы можете перебирать список учащихся вместо обращения к индексу 0.

 $result = json_decode($result, true); $result['response']['docs'][0]['student_id'] ... 

Почему бы просто не использовать один из PHP-клиентов для Solr, или PHP-ответчик? См. http://wiki.apache.org/solr/SolPHP

 $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>"; }