I am trying to create a JSON object from a string. I am new to PHP and I should probably be doing this using arrays but I'm not sure how to nest arrays in a loop. The part of the array I'm having a problem with is creating an array of dates. Only the last date object is shown after using json_encode
. If I echo the string, all of the dates are there. At first I tried appending the loop variable to the key and that works but is out of order when brought into iOS apparently so I can't append the loop variable. Here is my code. Any help or guidance would be greatly appreciated.
date_default_timezone_set('America/Los_Angeles');
$timezone = date_default_timezone_get();
$date1 = new DateTime($item['startdate']['S']);
$date2 = new DateTime($item['enddate']['S']);
$date = new DateTime(date('m/d/Y'));
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($date, $interval, $date2);
$to_time = date('H:i:s', strtotime($item['endtime']['S']));
$from_time = date('H:i:s a', time());
$loop = round(abs($to_time - $from_time));
$dv = 0;
foreach ($period as $dt) {
if ($dv == 30) break;
$spaces .= "\"dates\": {\"date\":\"" . $dt->format('m-d-Y') . "\",";
$spaces .= "\"timeslots\":{";
for ($i = 0;$i <= $loop; $i++) {
$spaces .= "\"timeslot" . $i . "\":\"" . date('H', time() + ($i*3600)) . ":00" . "\",";
}
$spaces = substr($spaces,0,-1);
$spaces .= "}},";
$dv++;
}