Search code examples
phparraysmultidimensional-arrayhierarchical-datadate-range

Build hierarchical multidimensional array with all year, month, day, and hour values within a range of years


I am trying to create a multidimensional array for Years, Months, Days, Hours so I can track certain data on an hourly basis. I am attempting to initialize this array through nested for loops but seem to be failing miserably at it.

$Year = array();

//This starts in 2015 and works until 2018
for($z=0; $z < 3; ++$z)
{
    $Month = array();
    array_push($Year, $Month);

    //Months
    for($a=0; $a < 12; ++$a)
    {
        //Days
        for($b=0; $b < GetDaysInMonth($a); ++$b)
        {
            $Day = array();
            array_push($Month, $Day);

            //Hours
            for($c = 0; $c < 24; ++$c)
            {
                $Hours = array(0);
                array_push($Day, $Hours);
            }
        }
    }
}

The goal is to initialize an array of size 24 for hours, push that into an array for days, push the days array into months and the months array into years. Every time I try to access the data it seems to not exist however. What am I doing wrong here?


Solution

  • You must array_push after each for

    $Years = array();
    //This starts in 2015 and works until 2018
    for($z=0; $z < 3; $z++) {
        $Year = array();
        //Months
        for($a=0; $a < 12; $a++) {
            $Month = array();
            //Days
            for($b=0; $b < GetDaysInMonth($a); $b++) {
                $Day = array();
                //Hours
                for($c = 0; $c < 24; $c++) {
                    $Hours = $c;
                    array_push($Day, $Hours); // push Hours into Day
                }
                array_push($Month, $Day); // push Days into Month
            }
            array_push($Year, $Month); // push Months into Year
        }
        array_push($Years, $Year); // push each Year in a var with all Years
    }
    

    Edit: I added a variable named $Years to store all the years