使用json_encode()时删除数组索引引用 [英] Removing array index reference when using json_encode()

查看:412
本文介绍了使用json_encode()时删除数组索引引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用jQuery的datepicker制作了一个小型应用程序.我正在从如下所示的JSON文件中为其设置不可用的日期:

I have made a small application using jQuery's datepicker. I am setting unavailable dates to it from a JSON file which looks like this:

{ "dates": ["2013-12-11", "2013-12-10", "2013-12-07", "2013-12-04"] }

我想检查给出的日期是否已经在此列表中,如果有,请删除它.我当前的代码如下:

I would like to check if a date given is already in this list and remove it if so. My current code looks like this:

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);
    }
}

我的问题是,在我再次对数组进行编码后,它看起来像这样:

My problem here is that after I encode the array again, it looks like this:

{ "dates": ["1":"2013-12-11", "2":"2013-12-10", "3":"2013-12-07", "4":"2013-12-04"] }

有没有一种方法可以在JSON文件中找到日期匹配并将其删除,而在编码后不会出现键?

Is there a way to find the date match in the JSON file and remove it, without the keys appearing after the encode?

推荐答案

使用 array_values() 问题:

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

为什么?因为您要取消设置数组的键而无需重新排序.因此,在此之后,将其保留在JSON中的唯一方法也将是编码键.但是,应用array_values()之后,您将获得有序的密钥(从0开始),可以对其进行正确编码,而无需包含密钥.

Why? Because you're unsetting array's key without re-ordering it. So after this the only way to keep that in JSON will be encode keys too. After applying array_values(), however, you'll get ordered keys (starting from 0) which can be encoded properly without including keys.

这篇关于使用json_encode()时删除数组索引引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆