開発メモ

開発用のメモです。

CakePHP 日付/カレンダーを作成

Controller

        public function index($y=null,$m=null) {
            $y=$y?:date("Y");
            $m=$m?:date("m");
            $array=array(
                date("Y/m/d",mktime(0,0,0,$m+0,1,$y)),
                date("Y/m/d",mktime(0,0,0,$m+1,0,$y))
            );

            $tsta=$array[0];
            $tend=$array[1];

            $i=0;
            while(strcmp(date('N',strtotime($tsta)),"7")) {
                $tsta=date("Y/m/d",strtotime($tsta." -1 day"));
            }
            while(strcmp(date('N',strtotime($tend)),"6")) {
                $tend=date("Y/m/d",strtotime($tend." +1 day"));
            }

            $calendar=array();
            $week=array();
            $header=array();
            $temp=$tsta;

            while(1==1) {
                if(count($week)==7) {
                    array_push($calendar,$week);
                    if(count($header)!=7) {
                        foreach($week as $key=>$value) {
                            array_push($header,date("D",strtotime($value)));
                        }
                    }
                    $week=array();
                }
                array_push($week,$temp);
                if(strtotime($tend)==strtotime($temp)) {
                    array_push($calendar,$week);
                    break;
                }
                $temp=date("Y/m/d",strtotime($temp." +1 day"));
            };
            foreach($calendar as $key=>$value) {
                foreach($value as $key2=>$value2) {
                    $calendar[$key][$key2]=intval(date("m",strtotime($value2)))!=intval($m)//
                        ?" "
                        :date("d",strtotime($value2));
                }
            }
            $this->set("calendar",$calendar);
            $this->set("header",$header);
        }

View

<table class="table table-bordered table-striped" id="table01">
    <tbody>
        <? echo $this->Html->tableHeaders(array_values($header)); ?>
        <? echo $this->Html->tableCells($calendar,array(),array(),true); ?>
    </tbody>
</table>
Twitter: @asahina_alice