PHP json_decode question

I am trying to use json_decode to concatenate multiple json objects and then transcode them. my json looks like this:

{ "core": { "segment": [ { "id": 7, "name": "test1" }, { "id": 4, "name": "test2" } ] } } 

I have a few of these json objects and would like to merge only the "segement" arrays for each to get something like this:

 { "segment": [ { "id": 7, "name": "test1" }, { "id": 4, "name": "test2" } ], "segment": [ { "id": 5, "name": "test3" }, { "id": 8, "name": "test4" } ] } 

right now in my php code, I have decrypted json by storing each "segmented" array in a string and then encoding json.

 public function handleJSON($json){ $decodeData = json_decode($json); $segment =$decodeData->core; return $segment; } public function formatJSON(){ $segments = ""; for ($i = 0; $i < count($json);$i++) { $segments .= handleJSON($json[$i]); } echo json_encode($segments); } 

when I do this, I get an error: Object of class stdClass cannot be converted to string

so I tried using them in an array:

 public function formatJSON(){ $segments = array(); for ($i = 0; $i < count($json);$i++) { $segments[$i] = handleJSON($json[$i]); } echo json_encode($segments); } 

this time I don't get an error message, but it stores my entire json merged object in array brackets. how can I just return a JSON object without being encapsulated in an array?

+6
json php
source share
2 answers

I think one way would be to use the second parameter json_decode , assoc :

"When TRUE, the returned objects will be converted to associative arrays."

I find it usually easier to deal with associative arrays than with the stdClass class.

 $str = '{ "core": { "segment": [ { "id": 7, "name": "test1" }, { "id": 4, "name": "test2" } ] } }'; print "<pre>"; print_r(json_decode($str)); print "</pre>"; print "<pre>"; print_r(json_decode($str,true)); print "</pre>"; 

First, a version of Object is created, and then an associative array:

 stdClass Object ( [core] => stdClass Object ( [segment] => Array ( [0] => stdClass Object ( [id] => 7 [name] => test1 ) [1] => stdClass Object ( [id] => 4 [name] => test2 ) ) ) ) Array ( [core] => Array ( [segment] => Array ( [0] => Array ( [id] => 7 [name] => test1 ) [1] => Array ( [id] => 4 [name] => test2 ) ) ) ) 

I think I would like to do something like: create a new empty array, decode as an associative array, grab the elements of the segment and insert it into a new empty array. So:

 $segments = array(); // assuming you had a bunch of items in the $strings array foreach ($strings as $str) { $item = json_decode($str,true); $segments = array_merge($item['core']['segment], $segments); } 

Now you can encode this for json as follows:

 $final_json = json_encode(array('segments'=>$segments)); 
+14
source share

The external object contains two elements named "segment". Although this is legal JSON, it is not possible to have a PHP object with two different elements with the same name.

+2
source share

All Articles