Jump to content

Recommended Posts

I would like to create an array from the one below that can sort of filter using date ranges;

 

For example, make an array that contains data using date <= 2018-05-09 without a loop.

 

A loop is an option just wondering if you can filter by keys somehow.

Array
(
    [2018-04-23 21:31:40] => -1.174
    [2018-04-24 15:43:59] => -1.015
    [2018-04-26 00:14:10] => -0.37
    [2018-04-30 18:41:51] => -1.042
    [2018-05-01 20:08:40] => -0.72
    [2018-05-02 22:11:52] => -0.107
    [2018-05-07 18:40:12] => -0.298
    [2018-05-09 16:35:38] => -0.36
    [2018-05-10 01:14:27] => 0.408
    [2018-05-14 20:49:54] => 1.549
)

Share this post


Link to post
Share on other sites

It's a little reckless, but I'm implementing the loop like this.

$d = date('Y-m-d', strtotime('last Sunday', strtotime(date('Y-m-d'))));
$d = $d." 23:59:59";
foreach($combine as $key => $b){
  if(strtotime($key) >= strtotime($d)){
    unset($combine[$key]);
  }
}

A filter that does the same would be awesome..

Share this post


Link to post
Share on other sites

Use the ARRAY_FILTER_USE_KEY flag

 

$arr = array_filter($arr, function($v) { return $v < '2018-05-09';}, ARRAY_FILTER_USE_KEY);

Share this post


Link to post
Share on other sites

Walked around array_filter for a while, never seen the ability to put that tag there. thanks!

Share this post


Link to post
Share on other sites

Rather than hardcoding the date as I did above

 

$sunday = (new DateTime('last sunday'))->format('Y-m-d');                                            
$arr = array_filter($arr, function($v) use ($sunday) { return $v < $sunday;}, ARRAY_FILTER_USE_KEY);

Share this post


Link to post
Share on other sites

great also changed the code from the last second on Sunday to the first on Monday.

 

looks like that works.

 

I appreciate the help, thanks.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.