先前感谢您提供建议。我有一个从REST服务检索的以下JSON。
"events": [
{
"id": 408,
"name": "My Test1",
"modulename": "test",
"instance": 0,
"timestart": 1470370500,
"timeduration": 864000,
},
{
"id": 418,
"name": "Quiz Open",
"modulename": "quiz",
"instance": 225,
"timestart": 1473737880,
"timeduration": 0,
},
{
"id": 423,
"name": "Quiz Close",
"modulename": "quiz",
"instance": 225,
"timestart": 1476665040,
"timeduration": 0,
},
{
"id": 409,
"name": "August event",
"modulename": "event",
"instance": 0,
"timestart": 1467295200,
"timeduration": 2474700,
}
]
我需要以下面的JSON格式读取JSON和输出
"output": [
{
"name":
"Start":
"End":
}
]
我的问题出现在名称为" Quiz"这是" modulename"在JSON输入中。测验将在日期(时间段)打开,模块名称为"测验"和"实例" - 225作为唯一标识符,以具有相同实例ID的不同日期(timestart)结束。 json在一个大数组中包含100个事件。我和#34;结束"在输出中,json对象是" timestart" +" timeduration"。
我的问题是,如果模块名称是" quiz"那么迭代的有效算法是什么?获取实例并遍历整个数组以查找实例的下一个出现并添加到输出json。有什么指针吗?
答案 0 :(得分:1)
如果你的json是这样的话,首先要确保你的json格式正确: -
$str='{"events": [
{
"id": 408,
"name": "My Test1",
"modulename": "test",
"instance": 0,
"timestart": 1470370500,
"timeduration": 864000
},
{
"id": 418,
"name": "Quiz Open",
"modulename": "quiz",
"instance": 225,
"timestart": 1473737880,
"timeduration": 0
},
{
"id": 423,
"name": "Quiz Close",
"modulename": "quiz",
"instance": 225,
"timestart": 1476665040,
"timeduration": 0
},
{
"id": 409,
"name": "August event",
"modulename": "event",
"instance": 0,
"timestart": 1467295200,
"timeduration": 2474700
}
]}';
然后你可以这样做....`
$arr=json_decode($str,true);
$result=array();
$prevInstance=array();
foreach($arr['events'] as $key=>$val){
if($val['modulename']=='quiz' && array_key_exists($val['instance'], $prevInstance)){
$k= $prevInstance[$val['instance']];
$result['output'][$k]['End']=$val['timestart'];
}else{
$tmp['name']=$val['name'];
$tmp['Start']=$val['timestart'];
$tmp['End']=$val['timeduration'];
$result['output'][$val['id']]=$tmp;
}
$prevInstance[$val['instance']]=$val['id'];;
}
$data=array();
foreach ($result['output'] as $ret){
$data['output'][]=$ret;
}
echo "<pre>";
echo json_encode($data);
答案 1 :(得分:0)
$array = json_decode($event,true); // first decode your retrieved array
$output = array();
foreach ($array as $key) { // then loop through it
if ($array[$key]['modulename'] == "quiz") { // only select if modulename is "quiz"
$obj = array("name" => $array[$key]['name'], "Start" => $array[$key]['timestart'], "END" => ($array[$key]['timestart'] + $array[$key]['timeend']));
array_push($output, $obj);
} else {
return;
}
}
返回json_encode($ output); //最后用于JSON中的输出,对输出数组进行编码
//output: [{"name":"quiz","Start":123,"END":579},{"name":"quiz","Start":123,"END":579},{"name":"quiz","Start":123,"END":579}]