I want to create an array with all the 5 minute times from 00:00 to 23:55
On this forum I found:
$minutes = 5;
$endtime = new DateTime('2012-01-01 09:00');
//modified the start value to get something _before_ the endtime:
$time = new DateTime('2012-01-01 00:00');
$interval = new DateInterval('PT' . $minutes . 'M');
while($time < $endtime){
$time->add($interval);
echo $time->format('Y-m-d H:i');
}
How do I change this so that the output can be used with json?
For example:-
$aArray = {"00:00":"00:00","00:05":"00:05", ......"23:55":"23:55"}
My problem is not in creating json, but in creating an hour/minute list without the date part.
You are allmost there, just little tweek and as Terje suggest using H:i. Perhaps something like this:
$startTime = new \DateTime('2010-01-01 00:00');
$endTime = new \DateTime('2010-01-01 23:55');
$timeStep = 5;
$timeArray = array();
while($startTime <= $endTime)
{
$timeArray[] = $startTime->format('H:i');
$startTime->add(new \DateInterval('PT'.$timeStep.'M'));
}
echo json_encode($timeArray);
The argument to DateTime::format
controlls the selection of fields like this:
To get only hour and minute: Use 'H:i'
as format string.
For more formatting options: See http://www.php.net/manual/en/function.date.php
And if you can't use the DateTime functions, I would have generated the array like this:
$times = array();
for ($h = 0; $h < 24; $h++){
for ($m = 0; $m < 60 ; $m += 5){
$time = sprintf('%02d:%02d', $h, $m);
$times["'$time'"] = "'$time'";
}
}
Try:
echo json_encode($Var);
This should do the trick.. View the manual here: http://www.php.net/manual/en/function.json-encode.php
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