杨__羊羊
由于数组的键之间没有直接链接,因此最简单的方法是使用嵌套循环。您只需要循环遍历$priceYear数组并检查每个“年份”值和YEAR中的值$array。如果它们匹配,您可以仅替换$priceYear数组中的该值。下面的代码带有注释,可以告诉您每一行的作用:// 1. loop through the nested arrays in $priceYearforeach ($priceYear as $key => $price_years_array) { foreach ($price_years_array as $index => $price_years_value) { // 2. Create a variable to store the new value for the year in this $priceYear array, // initialised to 0 (your specified default) $new_year = 0; // 3. check each year in your $array foreach ($array as $replacement_values){ // 4. if $replacement_values has a YEAR and VALUE_AMDON... // and $price_years_value matches the value in YEAR... if( $replacement_values['YEAR'] && $replacement_values['VALUE_AMDON'] && $replacement_values['YEAR'] == $price_years_value){ // 5. store this in our $new_year variable $new_year = $replacement_values['VALUE_AMDON']; } } // 6. after checking all years in $array, it we found a match it will be in $new_year // otherwise it will still be 0. // Now simple set this value - we can access this directly using $key and $index $priceYear[$key][$index] = $new_year; }}var_dump($priceYear);使用不存在的年份的示例数据:$priceYear = array( 'AZ' => array( 1 => 2021, 2 => 2020), // <-- 2021 doesn't exist in $array 'BY' => array( 0 => 2020, 1 => 2016), // <-- 2016 doesn't exist in $array 'CX' => array(1 => 2020, 2 => 2020, 3 => 2020), 'DW' => array(106 => 2019, 107 => 2019, 108 => 2019));$array = array( array('YEAR' => 2018, 'VALUE_AMDON' => 55), array('YEAR' => 2019, 'VALUE_AMDON' => 57), array('YEAR' => 2020, 'VALUE_AMDON' => 59));输出:Array( [AZ] => Array ( [1] => 0 // <-- value is 0 because year didn't exist in $array [2] => 59 ) [BY] => Array ( [0] => 59 [1] => 0 // <-- value is 0 because year didn't exist in $array ) [CX] => Array ( [1] => 59 [2] => 59 [3] => 59 ) [DW] => Array ( [106] => 57 [107] => 57 [108] => 57 ))