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开始),可以正确编码而不包括键.

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: <span id=&quot...
jQuery 添加水印 <script src="../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...