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 文件中找到日期匹配项并将其删除,而 key 不会出现在编码之后?

最佳答案

使用 array_values()对于您的问题:

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

为什么?因为您在不重新排序的情况下取消设置数组的键。因此,在此之后,将其保存在 JSON 中的唯一方法也将是编码键。但是,在应用 array_values() 之后,您将得到有序的键(从 0 开始),可以在不包括键的情况下正确编码。

https://stackoverflow.com/questions/20372982/

相关文章:

json - 在 node package.json 中,使用额外参数从另一个脚本调用脚本,在这种情

json - Play Framework - 向 JSON 对象添加字段

JSON Schema - 根据另一个字段的值指定字段

json - 使用 jq 从 JSON 输出中提取特定字段

ruby-on-rails - 销毁记录时应该渲染什么?

c# - 使用 JSON.NET 序列化/反序列化对象字典

jquery - 使用 jQuery grep() 过滤 JSON 数组

json - 应该如何为 RESTful JSON 集合实现 HATEOAS 样式的链接?

java - 可以将 Jackson 配置为从所有字符串属性中修剪前导/尾随空格吗?

json - 简单、安全的 API 认证系统