Brian
Brian

Reputation: 7326

PHP - Append new JSON object to nested array within JSON object

Setup

I have retrieved a JSON string from a URL using 'file_get_contents' and have subsequently decoded it using `json_decode'

$search_URL="http://abcdefg.com"
$json = file_get_contents($search_URL);
$obj = json_decode($json, true);

The JSON represents an Apache Solr search response:

{  
  "responseHeader":{  
    "status":0,
    "QTime":3,
    "params":{  
      "q":"zzzzzzz",
      "wt":"json"
    }
  },
  "response":{  
    "numFound":20690,
    "start":0,
    "docs":[  
      {  
        "title":"yyyyy-y-y-yyyyy-yy-y",
        "author":"author 1, author 2, author 3",
        "url":"https://yyyyy.com",
        "id":yyyy,
        "_version_":yyyyy
      },
      {  
        "title":"xxxx-x-x-xxxx-xxxx",
        "author":"author 1, author 2",
        "url":"https://xxxxx.com",
        "id":xxxxx,
        "_version_":xxxxxx
      },
  ]
}
}

I basically need to grab each author field in the docs[] array, split it by commas to get a new array

$author_array = explode(", ", $author);

I then need to call another web service with these author names that will return JSON. I would love to simply plug this JSON in to my existing JSON and send it all back

Question

I need to modify my JSON so that each doc contains this new JSON object. How can I do this?

{  
  "title":"xxxx-x-x-xxxx-xxxx",
  "author":"author 1, author 2",
  "url":"https://xxxxx.com",
  "id":xxxxx,
  "_version_":xxxxxx,
  "authors":[
    {
      "name": "author1",
      "id": "143"
    },
    {
      "name": "author2",
      "id": "72"
    }
  ]
}

My Attempt

I have tried a simpler version of this where I simply have an array of author names

{  
  "title":"xxxx-x-x-xxxx-xxxx",
  "author":"author 1, author 2",
  "url":"https://xxxxx.com",
  "id":xxxxx,
  "_version_":xxxxxx,
  "authors":[
    "author1",
    "author2"
  ]
}

I tried the following:

$response = $obj['response'];
$docs = $response['docs'];
foreach($docs as &$doc) {
    $author = $doc['author'];
    $authors_array = explode(" ,", $author);
    $doc['authors'] = $authors_array;
}

This has ultimately failed as the new array is not appended.

Upvotes: 0

Views: 360

Answers (1)

Barmar
Barmar

Reputation: 781370

Explode the author string, call the API on each element, make an array of all these results, and put it back into the object.

I use a reference below in foreach so it can modify the document element directly.

foreach ($obj['response']['docs'] AS &$doc) {
    $author_names = explode(',', $doc['author']);
    $author_array = array_map('author_api', $author_names);
    $doc['authors'] = $author_array;
}

Upvotes: 2

Related Questions