我使用 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 文件中找到日期匹配项并将其删除,而 key 不会出现在编码之后?
最佳答案
使用 array_values()
对于您的问题:
$arr['dates'] = array_values($arr['dates']);
//..
$arr = json_encode($arr);
为什么?因为您在不重新排序的情况下取消设置数组的键。因此,在此之后,将其保存在 JSON 中的唯一方法也将是编码键。但是,在应用 array_values()
之后,您将得到有序的键(从 0
开始),可以在不包括键的情况下正确编码。
https://stackoverflow.com/questions/20372982/