使用 json_encode() 时删除数组索引引用

2022-08-30 11:01:47

我使用jQuery的.我正在从JSON文件中设置不可用的日期,如下所示:datepicker

{ "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


答案 2

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

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

重新编制索引也应移到循环之外,多次重新编制索引是没有意义的。foreach


推荐