我正在尝试使用json_decode组合一些json对象然后重新编码它.我的json看起来像:
{ "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对象,而不是封装在一个数组?
我认为一种方法是利用第二个参数
json_decode,assoc:
原文链接:https://www.f2er.com/php/133094.html“When TRUE,returned objects will be
converted into associative arrays.”
我发现通常处理关联数组而不是stdClass类更容易.
$str = '{ "core": { "segment": [ { "id": 7,"name": "test2" } ] } }'; print "<pre>"; print_r(json_decode($str)); print "</pre>"; print "<pre>"; print_r(json_decode($str,true)); print "</pre>";
这首先产生Object版本,然后产生关联数组:
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 ) ) ) )
我想我会做类似的事情,创建新的空白数组,解码为关联数组,抓取段成员并将它们拼接到新的空白数组中.所以:
$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); }
现在,您可以将此编码为json,如下所示:
$final_json = json_encode(array('segments'=>$segments));