如果我的数组在另一个数组中不存在,我想获取它的日期。这是一个简单的逻辑,但我做不到
变量值
$date_ranges:
array:5[
0 => "2022-02-22 08:00:00"
1 => "2022-02-23 08:00:00"
2 => "2022-02-24 08:00:00"
3 => "2022-02-25 08:00:00"
4 => "2022-02-26 08:00:00"
]
$results:
0 => array:2[
"name" => "Steve"
"start_date" => "2022-02-22 08:00:00"
]
1 => array:2[
"name" => "Chelsea"
"start_date" => "2022-02-24 08:00:00"
]
2 => array:2[
"name" => "Azu"
"start_date" => "2022-02-26 08:00:00"
]
我在获得预期输出时遇到问题,我想将$results中不存在的$date_ranges的日期存储为数组。
预计日期:2022-02-23 08:00:00和2022-02-25 08:00:00
array:2[
0 => "2022-02-23 08:00:00"
1 => "2022-02-25 08:00:00"
]
使用$hash_map_times
存储HashMap以避免不必要的循环的示例。
沙盒
<?php
$input = [
"2022-02-22 08:00:00",
"2022-02-23 08:00:00",
"2022-02-24 08:00:00",
"2022-02-25 08:00:00",
"2022-02-26 08:00:00"
];
$times = [
[
"name" => "Steve",
"start_date" => "2022-02-22 08:00:00"
],
[
"name" => "Chelsea",
"start_date" => "2022-02-24 08:00:00"
],
[
"name" => "Azu",
"start_date" => "2022-02-26 08:00:00"
]
];
$hash_map_times = array_reduce($times, function ($carry, $item) {
$start_date = $item["start_date"];
if (!isset($carry[$start_date])) {
$carry[$start_date] = 1;
}
return $carry;
}, []);
$output = array_reduce($input, function ($carry, $item) use ($hash_map_times) {
if (!isset($hash_map_times[$item])) {
$carry[] = $item;
}
return $carry;
}, []);
print_r($output);
使用以下代码:
$resultArray = [];
foreach ($date_ranges as $dateRange) {
if (!in_array($dateRange, array_column($results, 'start_date'))) {
array_push($resultArray, $dateRange);
}
}
使用array_filter
可以工作。
$filtered = array_filter(
$date_ranges,
function ($item) {
return in_array($item, array_column($results, 'start_date'));
}
)
使用集合,它的可读性会更强一些。
$filtered = collect($date_ranges)
->filter(function ($item) use ($results) {
return collect($results)->contains('start_date', $item);
});