我需要解析给定的 JSON 文件,以查找通过 HTTP GET 传递的开始时间和结束时间之间发生的事件。在此范围内发生的事件应作为新的 JSON 编码响应返回。到目前为止,我已经提出了两种可能的解决方案。似乎都没有给我预期的 JSON 编码文件。
编辑:除了脚本未生成正确的 JSON 文件之外,我在 Chrome 上的开发人员控制台中收到以下错误: Uncaught TypeError: Cannot read property 'length' of 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
关于javascript - 解析 JSON 文件以生成并返回另一个包含所需数据的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23600856/