简体   繁体   中英

How to increment a given time with a given number of minutes and associate the new time to a array list

I need to increment a given time with a given minutes number and and associate the time with an array list of id's. An example of what I need :

$ids_arrays = array(699926900040821, 699926900040822, 699926900040823); 
$given_time='20:30'; 
$given_minutes = '5';
$newarray=array(); 

And I want to create a new array like this :

Array (
        [699926900040821] => '20:35'
        [699926900040822] => '20:40'
        [699926900040822] => '20:45' 
      )

My code :

//$_GET['grupuri']= simple array ,$ids_arrays;
//$_GET['numar_grup']=  number of minutes to increment ;
//$_GET['time_grup']=time array;
$ora_grup=array();
$h1=new DateTime($_GET['time_grup']);
$m1=new DateInterval('PT'.$_GET['numar_grup'].'M');
for ( $i=0; $h=$h1;  $h->format('H') <10;   $i <count($_GET['grupuri']) ;   $i++, $h->add($m1)) {    
    $ora_grup[$_GET['grupuri'][$i]]=$h->format("H:i\n");
}

Try this:

$ids_arrays = array('699926900040821', '699926900040822', '699926900040823'); 
$given_time = '20:30'; 
$given_minutes = '5';

$t = strtotime('today '. $given_time);
$newarray = array();
foreach ($ids_arrays as $id) {
    $newarray[$id] = date('H:i:s', $t += $given_minutes * 60);
}

This would do:

/**
 * @return array
 */
function associateIdsWithTime(
    array $ids, 
    DateTime $startTime, 
    DateInterval $interval
) {
    $associatedIds = array();

    foreach ($ids as $id) {
        $associatedIds[$id] = $startTime->add($interval)->format('H:i');
    }

    return $associatedIds;
}

Then you'd call it like this:

$associatedIds = associateIdsWithTime(
    array(699926900040821, 699926900040822, 699926900040823),
    DateTime::createFromFormat('H:i', $given_time),
    DateInterval::createFromDateString("+ $given_minutes minutes")
);

For $given_time = 20:30 and $given_minutes = 5 it will return:

Array
(
    [699926900040821] => 20:35
    [699926900040822] => 20:40
    [699926900040823] => 20:45
)

On a side note: take caution with your ids on 32bit systems. You are using integers but PHP_INT_MAX on 32bit systems is limited to 2.147.483.647, which cannot fit your 699.926.900.040.822. You might want to change to strings to keep it portable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM