Create an Array of the Last 30 Days Using PHP

前端 未结 5 1808

I am trying to create an array starting with today and going back the last 30 days with PHP and I am having trouble. I can estimate but I don’t know a good way of doing it

相关标签:
5条回答
  • 2020-12-20 13:46

    For those who want to show sales of the past X days,
    As asked in this closed question (https://stackoverflow.com/questions/11193191/how-to-get-last-7-days-using-php#=), this worked for me.

      $sales = Sale::find_all();//the sales object or array
    
      for($i=0; $i<7; $i++){
        $sale_sum = 0;  //sum of sale initial
        if($i==0){ 
        $day = strtotime("today"); 
      } else {
       $day = strtotime("$i days ago");
      }
      $thisDayInWords = strftime("%A", $day);
    
      foreach($sales as $sale){
        $date = strtotime($sale->date_of_sale)); //May 30th 2018 10:00:00 AM
        $dateInWords = strftime("%A", $date);
    
        if($dateInWords == $thisDayInWords){
            $sale_sum += $sale->total_sale;//add only sales of this date... or whatever
        } 
      } 
      //display the results of each day's sale
      echo $thisDayInWords."-".$sale_sum; ?> 
    
     } 
    

    Before you get angry: I placed this answer here to help someone who was directed here from that question. Couldn't answer there :(

    0 讨论(0)
  • 2020-12-20 13:46

    Here is advance latest snippet for the same,

    $today     = new DateTime(); // today
    $begin     = $today->sub(new DateInterval('P30D')); //created 30 days interval back
    $end       = new DateTime();
    $end       = $end->modify('+1 day'); // interval generates upto last day
    $interval  = new DateInterval('P1D'); // 1d interval range
    $daterange = new DatePeriod($begin, $interval, $end); // it always runs forwards in date
    foreach ($daterange as $date) { // date object
        $d[] = $date->format("Y-m-d"); // your date
    }
    print_r($d);
    

    Working demo.

    Official doc.

    0 讨论(0)
  • 2020-12-20 13:47

    You can use time to control the days:

    for ($i = 0; $i < 30; $i++)
    {
        $timestamp = time();
        $tm = 86400 * $i; // 60 * 60 * 24 = 86400 = 1 day in seconds
        $tm = $timestamp - $tm;
    
        $the_date = date("m/d/Y", $tm);
    }
    

    Now, within the for loop you can use the $the_date variable for whatever purposes you might want to. :-)

    0 讨论(0)
  • 2020-12-20 13:47
    $d = array();
    for($i = 0; $i < 30; $i++)
        array_unshift($d,strtotime('-'. $i .' days'));
    
    0 讨论(0)
  • 2020-12-20 13:55

    Try this:

    <?php    
    $d = array();
    for($i = 0; $i < 30; $i++) 
        $d[] = date("d", strtotime('-'. $i .' days'));
    ?>
    
    0 讨论(0)
提交回复
热议问题