简体   繁体   English

PHP过滤器多维数组

[英]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.如何过滤日期在 2019-05-01 和 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 ?因此,结果将有 ID 为 534 和 100 的元素。或者日期是 >= 2019-07-05 或日期是 <= 2019-01-01 ?

I know there is array_filter function, but cant understand how to use it in thus case?我知道有 array_filter 函数,但不明白在这种情况下如何使用它? 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.请务必查看 php.net 上的官方文档,因为它通常有大量示例和非常详尽的解释。

In your case you can compare dates as strings (since they are in Ymd format and comparing them alphabetically will do the trick):在您的情况下,您可以将日期作为字符串进行比较(因为它们采用 Ymd 格式并且按字母顺序比较它们就行了):

$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.通过使用array_filter()use关键字,您可以向过滤器提供变量 - 这可以是限制的开始和结束日期。

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.使用array_filter() ,如果回调中的return值为 true,则数据将保留在数组中,否则将被删除。 So then compare the dates, and see if they are greater than $from , and less than $to .然后比较日期,看看它们是否大于$from ,小于$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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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