ABOUTYOU
我认为最有效的方法是使用联合运算符。这应该这样做: <?php $data = array( "2018"=> array( "40" => 1, "41" => 1, "47" => 1, "48" => 1, "52" => 1 ), "2019"=> array( "1" => 1, "2" => 1, "6" => 1, "7" => 1 ) ); foreach($data as $year=>$array){ $keys = array_keys($array); $min = min($keys); $max = 52; if(!isset($data[$year+1])){ $max = max($keys); } $data[$year] = $data[$year] + array_fill($min,$max-$min+1, 0); ksort($data[$year]); } print_r($data); ?>输出:Array( [2018] => Array ( [40] => 1 [41] => 1 [42] => 0 [43] => 0 [44] => 0 [45] => 0 [46] => 0 [47] => 1 [48] => 1 [49] => 0 [50] => 0 [51] => 0 [52] => 1 ) [2019] => Array ( [1] => 1 [2] => 1 [3] => 0 [4] => 0 [5] => 0 [6] => 1 [7] => 1 ))
慕盖茨4494581
您可以使用一组数组函数,例如array_fill()和array_replace()来实现这一点。解释见评论$array = [ '2018' => [ '40' => 1, '41' => 1, '47' => 1, '48' => 1, '52' => 1 ], '2019' => [ '3' => 1, '4' => 1 ],];$result = []; // initialize result array$years = array_keys($array); // Get given years$first_year = min($years); // Get first year$last_year = max($years); // Get last yearforeach ($array as $year => $value) { // Loop thru each year array $weeks = array_keys($value); // Get weeks $start = 1; // Set first week $weeknum = 52; // Set number of weeks if ($year === $first_year) { // If first year, change number of weeks $start = min($weeks); $weeknum -= $start - 1; // number of weeks is 52 - the first week number - 1 } if ($year === $last_year) { // If last year, change number of weeks to last given week $weeknum = max($weeks); // Weeks will be 1 - last given week } $result[$year] = array_replace(array_fill($start, $weeknum, 0), $value);}var_dump($result);这样做的第一个目标是填充基于年份的数组。如果是第一年,则创建第一个给定周到第 52 周的数组如果是去年,则创建第 1 周到最后一周的数组如果在中间的某个地方,请创建第 1 周到第 52 周的数组然后用相同的键替换现有的数据数组