在数组中的数字范围和返回值之间进行迭代

时间:2014-05-01 21:03:58

标签: php json

我有一个困难,我有一个星期(5-8,12-13等)和JSON文件,我需要填补范围之间的差距。

我的JSON如下:

{
        "Name": "CHT2578/QGA/YEAR/Practical/01 <5-10, 12-16, 21-25, 27-32>",
        "Description": "TEAM PROJECT (MULTIMEDIA)",
        "Scheduled": "Checked",
        "Size": 25,
        "Required Staff Names": "Blogs, Joe",
        "Allocated Staff Name": "Blogs, Joe",
        "Allocated Location Name": "CW4/01",
        "Scheduled Weeks": "5-10, 12-16, 21-25, 27-32",
        "Scheduled Days": "Thursday",
        "Scheduled Start Time": "15:15",
        "Scheduled End Time": "17:15",
        "Who Scheduled": "test",
        "When Scheduled": "03/04/2014 10:13"
    }

到目前为止,我已设法输出如下:

[19] => TEAM PROJECT (MULTIMEDIA) - CW5/03 - Wednesday - 5
[20] => TEAM PROJECT (MULTIMEDIA) - CW5/03 - Wednesday - 10
[21] => TEAM PROJECT (MULTIMEDIA) - CW5/03 - Wednesday -  12
[22] => TEAM PROJECT (MULTIMEDIA) - CW5/03 - Wednesday - 16
[23] => TEAM PROJECT (MULTIMEDIA) - CW5/03 - Wednesday -  21
[24] => TEAM PROJECT (MULTIMEDIA) - CW5/03 - Wednesday - 25
[25] => TEAM PROJECT (MULTIMEDIA) - CW5/03 - Wednesday -  27
[26] => TEAM PROJECT (MULTIMEDIA) - CW5/03 - Wednesday - 32

使用以下代码我已经管理了上述输出:

public function formatTimeTable($file){
    $this->file = $file;
    $info[] = null;

    $string = file_get_contents($file);
    $json = json_decode($string, true);

        foreach ($json as $key => $value) {

        // does it contain a ,
        if (strpos($value['Scheduled Weeks'], ',') !== false) { 

        // explode on the ,
        $ex = explode(",", $value['Scheduled Weeks']);
            for($i = 0; $i < count($ex); $i++){

              if (strpos($ex[$i], '-') !== false) { 
                $ex2 = explode("-", $ex[$i]);
                foreach($ex2 as $key => $val){

                        $info[] .= $value['Description'] . " - " . $value['Allocated Location Name'] . " - " . $value['Scheduled Days'] . " - " . $val;

                }

              }
              else{
                $info[] .= $value['Description'] . " - " . $value['Allocated Location Name'] . " - " . $value['Scheduled Days'] . " - " . $ex[$i];
              }
            }
        }   
        else
        {
            $info[] .=  $value['Description'] . " - " . $value['Allocated Location Name'] . " - " . $value['Scheduled Days'] . " - " . $value['Scheduled Weeks'];
        }
    }
    return $info;
}

我的问题是:我是否能够在本周范围内+1,直到与最后一周相匹配?我试过:

  • 一个循环来迭代数字。
  • 一个for循环
  • 使用键值对的foreach循环一直是我得到的壁橱

谢谢。

1 个答案:

答案 0 :(得分:0)

使用strtotime

获取开始时间戳和结束时间戳,并使用这两个作为循环的边界。然后你可以做这样的事情:

$timestamp = /* get starting timestamp */;
$stoptime = /* get ending timestamp */;
while($timestamp < $stoptime) {
   $curWeek = date('Y-m-d', $timestamp); // Or however you need to format the week..
   // .. the rest of your output code ..

   // Update timestamp to the next week
   $timestamp = strtotime('+1 week', $timestamp);
}