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

 mobiledu2502924027 发布于 2023-02-12 21:42

我使用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文件中找到日期匹配并删除它,没有编码后出现的键?

任何帮助表示赞赏.

1 个回答
  • 使用array_values()您的问题:

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

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

    2023-02-12 21:51 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有