duanlian1978 2016-07-21 20:19
浏览 63

PHP foreach循环/ json_encode问题

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++;
}
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 ETLCloud 处理json多层级问题
    • ¥15 matlab中使用gurobi时报错
    • ¥15 这个主板怎么能扩出一两个sata口
    • ¥15 不是,这到底错哪儿了😭
    • ¥15 2020长安杯与连接网探
    • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
    • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
    • ¥15 可见光定位matlab仿真
    • ¥15 arduino 四自由度机械臂
    • ¥15 wordpress 产品图片 GIF 没法显示