在php中使用json_encode时删除数组索引引用

我使用jQuery datepicker创建了一个小应用程序。 我从json文件设置不可用的日期,如下所示:

 {"dates":["2013-12-11","2013-12-10","2013-12-07","2013-12-04"]}. 

我想检查一下给定的日期是否已经在此列表中,如果是,则将其删除。 我当前的代码如下所示:

 if(isset($_GET['date'])) //the date given { if($_GET['roomType']==2) { $myFile = "bookedDates2.json"; $date = $_GET['date']; if(file_exists($myFile)) { $arr = json_decode(file_get_contents($myFile),true); if (!in_array($date, $arr['dates'])) { $arr['dates'][] = $_GET['date']; //adds the date into the file if it is not there already } else { foreach ($arr['dates'] as $key => $value) { if (in_array($date, $arr['dates'])) { unset($arr['dates'][$key]); array_values($arr['dates']); } } } } $arr = json_encode($arr); file_put_contents($myFile,$arr); } 

我的问题是,在我再次编码数组后,它看起来像这样

 {"dates":["1":"2013-12-11","2":"2013-12-10","3":"2013-12-07","4":"2013-12-04"]} 

有没有办法在json文件中找到日期匹配并删除它,没有编码后出现的键?

任何帮助表示赞赏。

对您的问题使用array_values()

 $arr['dates'] = array_values($arr['dates']); //.. $arr = json_encode($arr); 

为什么? 因为你没有重新排序而没有设置数组的密钥。 所以在此之后,保持JSON的唯一方法也是编码密钥。 但是,应用array_values()后,您将获得有序键(从0开始),可以正确编码而不包括键。

您在现有尝试重新索引数组时忽略了array_values的返回值。 正确的是

 $arr['dates'] = array_values($arr['dates']); 

重建索引也应该移到foreach循环之外,多次重建索引没有意义。