<?php
$dates = [
['date_starts'=>'2021-03-22'],
['date_starts'=>'2022-04-22'],
['date_starts'=>'2023-05-22']
];
$current_year = date('Y');
foreach ($dates as $dt) {
$rates_results = [
['price'=>255, 'year'=>'2021'],
['price'=>200, 'year'=>'2021'],
['price'=>300, 'year'=>'2023']
];
// get the year from the start date. Since it's in YYYY-MM-DD format
// we can just use substr
$start_year = substr($dt['date_starts'], 0, 4);
// find matching years in $rates_results
$rate_keys = array_keys(array_column($rates_results, 'year'), $start_year);
// any matches?
if (empty($rate_keys)) {
// no, use the values from the current year instead
$rate_keys = array_keys(array_column($rates_results, 'year'), $current_year);
}
// get the actual rates
$code = 1;
$rates = array();
foreach ($rate_keys as $key) {
$rates[] = [
'custom' => $code,
'price' => $rates_results[$key]['price'],
'year' => $rates_results[$key]['year']
];
}
// output the rates
print_r($rates);
}