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?
json php
dtrainer45
source share