Search code examples
phppchart

PHP: Split unix timestamp range into 5 chuncks


I have a requirement where I need to extract 5 points from a Unix time stamp or PHP time stamp range.

For Example, From 2014-06-26 07:53:26 to 2014-06-27 07:52:46.

I need five points from these two dates in exact or approximate intervals, to chart using pChart.

Currently My Code is

$diff = $mintime->diff($maxtime);
$range = max($timestamps) - min($timestamps);
$cnt = count($timestamps);
$temp = ceil($range * (20/100));

for($i=0;$i<$cnt;$i++)
{
if($i%($cnt/5) == 0)
$point[$i] = gmdate("Y-m-d H:i:s",min($timestamps) + $temp * ($i+1));
else
$point[$i] = null;
}

But My Code returns erratic values. I know the problem is with the temp variable. Help me solve this.

Thanks


Solution

  • Try this:

    $from = '2014-06-26 07:53:26';
    $to = '2014-06-27 07:52:46';
    
    $diff_stamp = strtotime($to) - strtotime($from);
    $range = range(strtotime($from), strtotime($to), $diff_stamp/4);
    

    Here, $range is an array of timestamps. To convert each back to a date, you could use array_map:

    $range = array_map(function($a){return date('Y-m-d H:i:s', $a);}, $range);
    

    See Demo Updated


    Resources: strtotime(), range(), array_map()