繁体   English   中英

从单独的变量创建多维数组

[英]Creating a multidimensional array from separate variables

我有许多变量,用于存储该月的年,月和一系列日期(两个独立的月份中有两个)。 然后,我需要将它们合并到我认为是多维数组的位置(以前从未使用过这些类型的数组)。 这是我的具有变量的代码:

    // 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从字符串创建数组:

$daysArray = array($year1 => $month1 => explode(' ', $dates1), $year2 => $month2 => explode(' ', $dates2));

考虑到一些极端情况(同一年等),我认为这是一个相当简单(可读)的解决方案:

// 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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM