NEO
NEO

Reputation: 2001

How to parse a json in php

I am parsing the below json in php

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

using json_decode and looping through the result array I could get the individual elements in the docs section,

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

I am now trying to figure out in getting the values from the highlighting section of this json. I want to get the text fields in the highlighting part and store it in a array.

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

The array should be like this,

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

How to achieve this? Is there any way to map the id element of the docs to the number specified in the highlighting part?

Upvotes: 1

Views: 76

Answers (1)

The Alpha
The Alpha

Reputation: 146191

You may try this (Example)

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

Result :

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

Upvotes: 3

Related Questions