Php 从单独的变量创建多维数组
我有许多变量,存储一年、一个月和该月的一系列日期,其中有两个变量用于两个单独的月份。然后我需要将它们合并到一个多维数组中,我相信这个多维数组以前从未使用过这些类型的数组。以下是我的代码,其中包含变量:Php 从单独的变量创建多维数组,php,arrays,Php,Arrays,我有许多变量,存储一年、一个月和该月的一系列日期,其中有两个变量用于两个单独的月份。然后我需要将它们合并到一个多维数组中,我相信这个多维数组以前从未使用过这些类型的数组。以下是我的代码,其中包含变量: // Set the default timezone date_default_timezone_set('Australia/Sydney'); $month1 = date('m'); $year1 = date('Y'); $dates1 = '
// Set the default timezone
date_default_timezone_set('Australia/Sydney');
$month1 = date('m');
$year1 = date('Y');
$dates1 = '3 5 6 10 12 13 17 19 20 24 26 27 31';
$month2 = date('m', strtotime('first day of next month')) ;
$year2 = date('Y', strtotime('first day of next month')) ;
$dates2 = '10 15 26';
使用2013年12月10日作为当前日期和上述日期列表,我需要以以下格式的数组结束:
array("year" => array("month" => array(days)));
看起来是这样的:
$daysArray = array ("2013" => array("12" => array(3,5,6,10,12,13,17,19,20,24,26,27,31)), "2014" => array("1" => array(10,15,26)));
我不知道如何将这6个变量转换为多维数组?您可以使用explode从字符串创建数组:
考虑到一些边缘情况以及同一年的情况等,我认为这是一个相当简单易读的解决方案:
// Sample data
$month1 = 12;
$year1 = 2013;
$dates1 = '3 5 6 10 12 13 17 19 20 24 26 27 31';
$month2 = 1;
$year2 = 2014;
$dates2 = '10 15 26';
$result = combineDateArrays(createDateArray($year1, $month1, $dates1), createDateArray($year2, $month2, $dates2));
function createDateArray($year, $month, $dates) {
return array($year=>array($month=>explode(" ", $dates)));
}
function combineDateArrays($dateArray1, $dateArray2) {
foreach($dateArray2 as $year=>$months) {
foreach($months as $month=>$days) {
if (!isset($dateArray1[$year])) $dateArray1[$year] = array();
$dateArray1[$year][$month] = $days;
}
}
return $dateArray1;
}
谢谢@Ronald Swets-这很有效。我需要保留月份数字的前导零[我使用$month1=date'm']。数组中可以保留前导零吗?可以保留前导零,但必须确保所有内容都是字符串而不是整数。您可以通过在数字之前连接空字符串或强制转换为字符串来强制执行此操作
// Sample data
$month1 = 12;
$year1 = 2013;
$dates1 = '3 5 6 10 12 13 17 19 20 24 26 27 31';
$month2 = 1;
$year2 = 2014;
$dates2 = '10 15 26';
$result = combineDateArrays(createDateArray($year1, $month1, $dates1), createDateArray($year2, $month2, $dates2));
function createDateArray($year, $month, $dates) {
return array($year=>array($month=>explode(" ", $dates)));
}
function combineDateArrays($dateArray1, $dateArray2) {
foreach($dateArray2 as $year=>$months) {
foreach($months as $month=>$days) {
if (!isset($dateArray1[$year])) $dateArray1[$year] = array();
$dateArray1[$year][$month] = $days;
}
}
return $dateArray1;
}