Home » Php » php – Removing array index reference when using json_encode()

php – Removing array index reference when using json_encode()

Posted by: admin February 25, 2020 Leave a comment

Questions:

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"] }

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

How to&Answers:

Use array_values() for your issue:

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

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.

Answer:

You are ignoring the return value of array_values in your existing attempt to reindex the array. Correct is

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

The reindexing should also be moved outside the foreach loop, there is no point in reindexing multiple times.