【发布时间】:2009-11-11 08:11:13
【问题描述】:
我正在尝试使用 json_decode 来组合一些 json 对象,然后对其进行重新编码。我的 json 看起来像:
{
"core": {
"segment": [
{
"id": 7,
"name": "test1"
},
{
"id": 4,
"name": "test2"
}
]
}
}
我有一些这样的 json 对象,并且想只为每个组合“段”数组以获得如下结果:
{
"segment": [
{
"id": 7,
"name": "test1"
},
{
"id": 4,
"name": "test2"
}
],
"segment": [
{
"id": 5,
"name": "test3"
},
{
"id": 8,
"name": "test4"
}
]
}
现在在我的 php 代码中,我正在解码 json,将每个“段”数组存储到一个字符串中,然后对 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 对象,而不被封装在一个数组中?
【问题讨论】: