Home > database >  Filter and remove array item after 3 weeks of its creation in `php`
Filter and remove array item after 3 weeks of its creation in `php`

Time:10-01

How can the array item be filterd and removed from the array if it has been 3 weeks from its createdDate and if the status is Closed ?

bills:[
  {
   id: 1,
   createdDate: 1547640673837, //16th Jan 2019
   status:"Closed"
  },
  {
   id: 2,
   createdDate: 1626330034676, //15th July 2021
   status:"New"
  },
  {
   id: 3,
   createdDate: 1627626311000, //30th July 2021
   status:"Closed"
  },
  {
   id: 4,
   createdDate: 1631868710891, //17th Sept 2021
   status:"Closed"
  },
 {
   id: 5,
   createdDate: 1632983108, //30th Sept 2021
   status:"Closed"
  }
...
]
        

The bills array should have id:2,id:3,id:4; as of current date

CodePudding user response:

foreach($bills as $bill){
   $checked_date = Carbon\Carbon::parse($bill->createdDate)->addWeek(3)->format('m-d-Y');
   if($checked_date <= today()->format('m-d-Y')){
      $bill->delete();
   }
}

CodePudding user response:

Stack Overflow is unlikely to do the hard work for you but here's some pointers :

  1. Get the current Unix timestamp (hint - time())

  2. Remove three weeks from it (hint - 604800 seconds in a week).

  3. Loop through your existing array and compare the timestamp for each elements against the timestamp you get from 2. above.

  4. Remove elements from arrays using unset()

  • Related