我在这里有一个用户数组,该数组有2个以上的用户,每个用户数组都有一个registration_date,licence_expiry_date,性别,电子邮件,年龄和姓名。
数组看起来像这样。
$Users = Array(
(0) => Array
(
(id) => '100',
(name) => 'Name & Surname',
(email) => 'email@email.com',
(age) => '25',
(gender) => 'male',
(registration_date) => '2019-01-03',
(licence_expiry_date) => '2019-09-03',
),
(1) => Array
(
(id) => '101',
(name) => 'Name & Surname 1',
(email) => 'email1@email.com',
(age) => '22',
(gender) => 'male',
(registration_date) => '2019-03-03',
(licence_expiry_date) => '2019-02-03',
),
(2) => Array
(
(id) => '102',
(name) => 'Name & Surname 1',
(email) => 'email1@email.com',
(age) => '25',
(gender) => 'male',
(registration_date) => '2019-01-03',
(licence_expiry_date) => '2019-09-03',
),
(3) => Array
(
(id) => '103',
(name) => 'Name & Surname 3',
(email) => 'email3@email.com',
(age) => '25',
(gender) => 'male',
(registration_date) => '2019-08-03',
(licence_expiry_date) => '2019-10-03',
),
(4) => Array
(
(id) => '103',
(name) => 'Name & Surname 4',
(email) => 'email4@email.com',
(age) => '18',
(gender) => 'female',
(registration_date) => '2018-01-03',
(licence_expiry_date) => '2019-12-03',
),
);
我要实现的是将其中的数据过滤到另一个具有一定条件的数组。例如,我希望仅针对年龄为25岁且registration_date在2019-01-01之后,而licence_expiry_date在2019-10-01之后的用户进行过滤。
预期结果如下所示
$UsersFiltered = Array(
(0) => Array
(
(id) => '100',
(name) => 'Name & Surname',
(email) => 'email@email.com',
(age) => '25',
(gender) => 'male',
(registration_date) => '2019-01-03',
(licence_expiry_date) => '2019-09-03',
),
(2) => Array
(
(id) => '102',
(name) => 'Name & Surname 1',
(email) => 'email1@email.com',
(age) => '25',
(gender) => 'male',
(registration_date) => '2019-01-03',
(licence_expiry_date) => '2019-09-03',
),
);
答案 0 :(得分:3)
您可以使用array_filter
:
$UsersFiltered = array_filter($Users, function ($v) {
return $v['age'] == 25 &&
$v['registration_date'] > '2019-01-01' &&
$v['licence_expiry_date'] < '2019-10-01';
});
请注意,由于您的日期为YYYY-MM-DD
格式,因此可以按字母顺序进行比较,而无需转换为DateTime
对象,时间戳或类似内容。
答案 1 :(得分:2)
您可以使用array_filter,
$arr = array_filter($arr, function($val){
return ($val['age'] == 25 && strtotime($val['registration_date']) > strtotime('2019-01-01') && strtotime($val['licence_expiry_date']) < strtotime('2019-10-01'));
});
Demo。
我使用>和<作为严格的比较,因为您没有提到大于或小于等于。
我使用strtotime进行日期比较。
答案 2 :(得分:1)
您可以像这样使用array_filter:
$licence_expiry_date = new DateTime('2019-10-01 00:00:00');
$registration_date = new DateTime('2019-01-01 00:00:00');
$UsersFiltered = array_filter($Users, function($element) use ($licence_expiry_date, $registration_date) {
return $element['age'] == 25
&& DateTime::createFromFormat('Y-m-d', $element['registration_date']) > $registration_date
&& DateTime::createFromFormat('Y-m-d', $element['licence_expiry_date']) < $licence_expiry_date;
});