我正在尝试使用json_decode组合一些json对象然后重新编码它.我的json看起来像:
@H_301_21@{ "core": { "segment": [ { "id": 7,"name": "test1" },{ "id": 4,"name": "test2" } ] } }
我有一些这些json对象,并希望只为每个组合“segement”数组得到这样的东西:
{ "segment": [ { "id": 7,"name": "test1" },{ "id": 4,"name": "test2" } ],"segment": [ { "id": 5,"name": "test3" },{ "id": 8,"name": "test4" } ] }
现在在我的PHP代码中,我正在解码json,将每个“segment”数组存储到一个字符串中,然后编码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); }
当我这样做时,我收到一个错误:
类stdClass的对象无法转换为字符串
所以我尝试将它们存储在一个数组中:
public function formatJSON(){ $segments = array(); for ($i = 0; $i < count($json);$i++) { $segments[$i] = handleJSON($json[$i]); } echo json_encode($segments); }
这一次,我没有得到错误,但它将我的整个组合json对象存储在数组括号中.我怎么能只返回JSON对象,而不是封装在一个数组?