How to Create Nested Array PHP-ThrowExceptions

Exception or error:

My dataset is:
enter image description here

I want to organize the in the following json format:

data: {
    'year' : 2014,
    'year_data' : {
        'month' : 'January',
        'month_data' : {
            'day' : {
                '1' : 100,
                '2' : 200,
                '3' : 300,
                '4' : 400,
            }
        }
    }
}

Here is my approach:

function sheetData($data, $sheet) {
    echo "<pre>";
    $years = ['2014', '2015', '2016', '2017', '2018'];
    $months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 
    'August', 'September', 'October', 'November', 'December'];

    $x = 1; 
    $segment = 0;
    $segment_end = 11;
    $year_count = 0;
    $calc_years = [];
    $calc_months = [];
    while($x <= $sheet['numRows']) {
        $y = 3;
        if ($segment == $segment_end) { 
            $calc_months[$segment] = $months[$segment];
            $segment = 0;
            $calc_years[$year_count] = $years[$year_count];
            $year_count++;
        } else { 
            $calc_months[$segment] = $months[$segment];
            $segment++;
        }
        $col = 0;
        while($y <= $sheet['numCols']) {
            $cell = isset($sheet['cells'][$x][$y]) ? $sheet['cells'][$x][$y] : '';
            $calc_days[$col] =  $cell;
            $y++;
            $col++;
        }  
        $x++;
    }

    $data_year = array();
    $data_month = array();
    $data_day = array();
    $data_array = array();
    $count = 0;

    $count_years = count($calc_years);
    $count_months = count($calc_months);
    $count_days = count($calc_days);

    for ($p=0; $p < $count_years ; $p++) { 
      $data_array[$p]['year'] = $calc_years[$p];
      for ($q=0; $q < $count_months; $q++) {
        $data_array[$p]['year_data'][$q]['month'] = $calc_months[$q];
        for ($r=0; $r < $count_days; $r++) {
          $data_array[$p]['year_data'][$q]['month']['day'][$r] = $calc_days[$r];
        }
      }

    }

    var_dump($data_array);
}

I read the data from sheet and segmented as years, months and day in seperate arrays and lastly tried to write an array to populate the format i want. But
I am struggling to create nested array out of this. Tried in several ways but no solution. Any help?

Full Code link: enter link description here

Sample : https://drive.google.com/open?id=1NDpd0-sEMn47JDfhMagAjRnr_MemZttA

How to solve:

I find it’s easiest to use the square bracket array notation in PHP:

$array = [
  "data" => [
    "year" => 2014,
    "year_data" => [
      "month" => "January",
      "month_data" => [
        "day" => [
          "1" => 100,
          "2" => 200,
          "3" => 300,
          "4" => 400
        ]
      ]
    ]
  ]
];

You can then convert this array, into a JSON string like this:

json_encode($array);

Leave a Reply

Your email address will not be published. Required fields are marked *