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?
The json_encode() function is used to encode a value to JSON format.
JSON data structures are very similar to PHP arrays. PHP has built-in functions to encode and decode JSON data. These functions are json_encode() and json_decode() , respectively. Both functions only works with UTF-8 encoded string data.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With