php - php循环显示当前年份数据,如果没有找到而不是跳过
问题描述
所以我在一个循环中有一个循环都有年份数据,我试图弄清楚如果年份不匹配或存在于循环中而不是使用 continue 跳过条目,如何显示当前年份(2021 年)数据,任何想法或解决方案表示赞赏。
实时代码:http ://sandbox.onlinephpfunctions.com/code/b7cbef0613636aa41a41a7d5f283a2569ece9cb0
$dates = [
['date_starts'=>'2021-03-22'],
['date_starts'=>'2022-04-22'],
['date_starts'=>'2023-05-22']
];
foreach( $dates as $dt ){
$start_date = $dt['date_starts'];
$rates_results = [
['price'=>255,'year'=>'2021'],
['price'=>300,'year'=>'2023']
];
$rateIDs = [];
if ($rates_results) {
foreach ($rates_results as $rates) {
if(date("Y", strtotime($start_date)) !== ''.$rates['year'].''){
continue;
}
$rateIDs [] = [
'year' => $rates['year'],
'price' => $rates['price']
];
}
}
print_r($rateIDs);
}
所以这是我得到的输出:
Array
(
[0] => Array
(
[year] => 2021
[price] => 255
)
)
Array
(
)
Array
(
[0] => Array
(
[year] => 2023
[price] => 300
)
)
这就是我正在寻找的结果:
Array
(
[0] => Array
(
[year] => 2021
[price] => 255
)
)
Array
(
[0] => Array
(
[year] => 2021
[price] => 255
)
)
Array
(
[0] => Array
(
[year] => 2023
[price] => 300
)
)
解决方案
我认为你在嵌套 for 循环时过于复杂了。实际上,您有一个dates
数组和一个rates
数组,并且您想将一个与另一个交叉引用?
为此,您需要循环遍历dates
数组,然后使用 PHParray_*
函数查找特定年份的键;然后,如果什么也没找到,则使用当前年份。
$dates = [
['date_starts'=>'2021-03-22'],
['date_starts'=>'2022-04-22'],
['date_starts'=>'2023-05-22']
];
$rates_results = [
['price'=>255,'year'=>'2021'],
['price'=>300,'year'=>'2023']
];
$rate_year_array = array_column($rates_results, "year"); // Extract year "column" from $rates_results
foreach ($dates as $date_row) {
$search_year = date("Y", strtotime($date_row["date_starts"])); // Get the year to look up from the date supplied
$rate_key = array_search($search_year, $rate_year_array); // Search the "year" array and get the key for the current year
// If not found then the value will be (bool) false
if ($rate_key === false) { // Check if the key was found
$rate_key = array_search(date("Y"), $rate_year_array); // If not find the key for the current year
}
// Output the date to an array
$rateIDs[] = [
'year' => $rates_results[$rate_key]["year"],
'price' => $rates_results[$rate_key]["price"],
];
}
print_r($rateIDs); // Print the array
输出:
Array
(
[0] => Array
(
[year] => 2021
[price] => 255
)
[1] => Array
(
[year] => 2021
[price] => 255
)
[2] => Array
(
[year] => 2023
[price] => 300
)
)
推荐阅读
- python - 使用 python 脚本在 azure 上创建存储时出错,出现错误消息“TypeError:__init__() 恰好需要 1 个参数(给定 2 个)”
- javascript - 部署后 Firebase 消息传递未获得令牌
- spring - 如果请求没有额外的字段,则进行 Spring 字段验证
- javascript - 如何结合日期时间值和时间值打字稿
- ios - 在 Xcode 中调试时,我可以在返回之前找出返回值吗?
- google-cloud-functions - 如何在前端使用本地托管的 Firebase 功能 URL?
- elasticsearch - RSpec 和 Elasticsearch 导致 CI 失败
- java - Java中ArrayList的retainAll和removeAll的时间复杂度是多少。
- maven - 从 artifactid 拉变量
- python - 前缀 IV 值 AES 加密产生错误