如何在php中解析json

时间:2013-11-28 00:55:39

标签: php arrays json

我在php

中解析下面的json
{
  "responseHeader":{
    "status":0,
    "QTime":22,
    "params":{
      "fl":"title,id",
      "indent":"true",
      "q":"einstein",
      "hl.simple.pre":"<em>",
      "hl.simple.post":"</em>",
      "wt":"json",
      "hl":"true",
      "rows":"3"}},
  "response":{"numFound":63,"start":0,"docs":[
      {
        "id":"1",
        "title":"Albert Einstein"},
      {
        "id":"2088",
        "title":"Nationalism"},
      {
        "id":"1551",
        "title":"Dean Koontz"}]
  },
  "highlighting":{
    "1":{
      "text":[" for school exam September The Collected Papers of Albert <em>Einstein</em> Vol Doc s Unthinking for authority"]},
    "2088":{
      "text":[" in a letter to Alfred Kneser June Doc in The Collected Papers of Albert <em>Einstein</em> Vol Nationalism"]},
    "1551":{
      "text":[" changes since meeting Travis Did you get the leash on him yet <em>Einstein</em> Part Chapter Nora s query during"]}}}

使用json_decode并循环遍历结果数组我可以获得docs部分中的各个元素,

foreach ($myArray['response']['docs'] as $doc) {
        echo $doc['id'] . "<br/>";
        echo $doc['title'] . "<br/>";
    }

我现在正试图弄清楚从这个json的突出显示部分获取值。我想在突出显示部分中获取文本字段并将其存储在数组中。

"highlighting":{
    "1":{
      "text":[" for school exam September The Collected Papers of Albert <em>Einstein</em> Vol Doc s Unthinking for authority"]},
    "2088":{
      "text":[" in a letter to Alfred Kneser June Doc in The Collected Papers of Albert <em>Einstein</em> Vol Nationalism"]},
    "1551":{
      "text":[" changes since meeting Travis Did you get the leash on him yet <em>Einstein</em> Part Chapter Nora s query during"]}}}

数组应该是这样的,

"1" => " for school exam September The Collected Papers of Albert <em>Einstein</em> Vol Doc s Unthinking for authority"

"2088" => " in a letter to Alfred Kneser June Doc in The Collected Papers of Albert <em>Einstein</em> Vol Nationalism"

如何实现这一目标?有没有办法将docs的id元素映射到突出显示部分中指定的数字?

1 个答案:

答案 0 :(得分:3)

您可以尝试此操作(Example

$myArray  = json_decode($json, true);
$highlighting = array();
foreach($myArray['highlighting'] as $key => $value)
{
    $highlighting[$key] = $value['text'][0];
}

结果:

Array (
    [1] =>  for school exam September...
    [2088] =>  in a letter to Alfred ...
    [1551] =>  changes since meeting ...
)