简体   繁体   中英

Php filter multidimensional array

I have array like this:

arr=[
   627=[
   'lead_data'=>['name'=>'Name1',  'date'=>'2019-04-09']
   ],
   500=[
   'lead_data'=>['name'=>'Name2',  'date'=>'2018-05-07']
   ],
   534=[
  'lead_data'=>['name'=>'Name3',  'date'=>'2019-07-10']
   ],
  100=[
  'lead_data'=>['name'=>'Name4',  'date'=>'2019-05-12']
  ],

 ]

How can I filter this array where date is between 2019-05-01 and 2019-07-12. So in result there will be elements with ids 534 and 100. Or date is >= 2019-07-05 or date is <= 2019-01-01 ?

I know there is array_filter function, but cant understand how to use it in thus case? Please help, thanks

The simplest solution would to just iterate over your data like so:

 <?php
        $begin = date('Y-m-d', strtotime("2019-05-01"));
        $end = date('Y-m-d', strtotime("2019-07-12"));

        foreach($array as $key => $data) 
        {
           $date = date('Y-m-d', strtotime($$data['date']));
           if (($$data > $begin) && ($date < $end)){
               unset($array[$key]);
           }
        }
        var_dump($array);

Always make sure you check out official documentation on php.net because it usually have tons of examples and very thorough explanations.

In your case you can compare dates as strings (since they are in Ymd format and comparing them alphabetically will do the trick):

$filtered = array_filter($arr, function ($item) {
    return ($item['lead_data']['date'] > '2019-05-01') && ($item['lead_data']['date'] < '2019-07-12');
});

By using array_filter() , and using the use keyword, you can supply variables into the filter - this can be the start- and end-dates for your limits.

When using array_filter() , the data will remain in the array if the return value inside the callback is true, otherwise it will be removed. So then compare the dates, and see if they are greater than $from , and less than $to .

$from = '2019-05-01';
$to = '2019-07-12';
$result = array_filter($arr, function ($v) use ($from, $to) {
    return $v['lead_data']['date'] > $from && $v['lead_data']['date'] < $to;
});
print_r($result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM