Jump to content

Filter array by KEY


KillGorack
Go to solution Solved by Barand,

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
)
Link to comment
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..

Link to comment
Share on other sites

  • Solution

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);
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.