我需要解析给定的JSON文件,以查找通过HTTP GET传递的在开始时间和结束时间之间发生的事件。在这个范围内发生的事件应该作为一个新的JSON编码响应返回。到目前为止,我已经提出了两种可能的解决方案。似乎都没有给我预期的JSON编码文件。
编辑:除了脚本不产生适当的JSON文件,我在Chrome上的开发人员控制台得到以下错误:未捕获的TypeError:无法读取null属性'长度'
解决方案1:
$param1 = $_GET['startTime'];
$param2 = $_GET['endTime'];
$data = file_get_contents('./events.json');
$json = json_decode($data, true);
foreach ($json as $key => $value){
if ($value > $param1 && $value < $param2) {
echo "$key => $value"; }
else { return; }
}
解决方案2(传入的参数相同,每个循环不同):
foreach ($json as $key => $value){
if ($value >= $param1 && $value <= $param2) {
$tempFile = "tempEvents.json";
$jsonArray = json_decode(file_get_contents($tempFile), true);
array_push($jsonArray, array( 'title' => ????, 'start' => $param1, 'end' => $param2 ));
file_put_contents($file, json_encode($jsonArray));
}
else { return; }
echo json_encode('tempEvents.json');
}
要解析的JSON文件示例:
[
{
"Name":"Event 1",
"Start Time":258147369,
"End Time":369147258
},
{
"Name":"Event 2",
"Start Time":789456123,
"End Time":159487263
},
]
您应该在数组上使用json_encode
以获得格式良好的JSON输出。我不能为你的if语句的有效性说话,因为你没有提供任何样本数据,但这就是你应该如何做你的转换:
$param1 = $_GET['startTime'];
$param2 = $_GET['endTime'];
$data = file_get_contents('./events.json');
$json = json_decode($data, true);
$output = array();
foreach ($json as $key => $value){
if ($value > $param1 && $value < $param2)
$output[$key] = $value;
}
$json_out = json_encode($output);
echo $json_out; // this outputs to the browser
// to output to file, use $json_out as your string to write to file