我希望在名为 week_year 的表格中使用以下架构:
Week_year = {id, week, year}
要插入每年的周数,以便2001年有第1周,第2周,第3周,......,第52周,然后从2002年开始直到2009年。
我尝试过不同的PHP脚本,但似乎无法正确使用它。我尝试了不同的表,一年一年,一周一周,然后给每周一年_id,但这似乎没有效果。
我希望有人可以帮助我创建,我相信是一个简单的PHP循环来生成这些数字并将它们插入我的MySQL数据库。
添加了作为答案发布的其他信息
我尝试过这段代码,这是一年中无休止的循环:
<?php
$year = 2001;
$week_start = 1;
$week_end = 52;
for ( $week_start = 1; $week_start <= 52; $week_start++ ) {
echo $week_start;
echo "<br />";
for ($week_start = 1; $week_start <= 52; $year++) {
echo $year;
echo "<br />";
}
}
?>
答案 0 :(得分:3)
在SQL中执行此操作,而不是PHP:
create table artificial_range( int id not null auto_increment, ci int);
insert into artificial_range(c1) values (1);
- 现在加上artificial_range的大小
insert into artificial_range(c1) select c1 from artificial_range;
- 重复上述插入五次; - 你现在在artificial_range
中有64行-- now insert into week_year:
insert into week_year(week, year)
select a.id, b.id + 2000
from
artificial_range a,
artificial_range b
where a.id < 53 and b.id < 10;
-- or even better, just make week_year a view:
create view week_year as
select a.id as week, b.id + 2000 as year
from
artificial_range a,
artificial_range b
where a.id < 53 and b.id < 10;
有一点需要注意:根据“周”的含义,有些年份有53周。
答案 1 :(得分:2)
$id_start = 1;
for ($year=2002; $year<=2009; $year++) {
$values = array();
for ($week=1; $week<=52; $week++) {
$values[] = implode(',', array($id_start++, $week, $year));
}
$query = 'INSERT INTO `week_year` (id, week, year) '
. 'VALUES (' . implode('),(', $values) . ')';
$db->query($query);
}
** 注意 **查看localtime() PHP函数。您不需要有一个包含周/年的表,只需要一个时间戳,并使用该时间戳与$info = localtime($row->timestamp, true)
并使用$weekNumber = floor($info['tm_yday'] / 7);
来获取您的周数。只是一个想法。
答案 2 :(得分:0)
从php脚本中调用populate_year_week(2001,2009)存储过程!
drop table if exists year_week;
create table year_week
(
year_id smallint unsigned not null,
week_id tinyint unsigned not null,
primary key (year_id, week_id)
);
delimiter ;
drop procedure if exists populate_year_week;
delimiter #
create procedure populate_year_week
(
in from_yr smallint unsigned,
in to_yr smallint unsigned
)
proc_main:begin
declare yr smallint unsigned default 0;
declare wk tinyint unsigned default 0;
truncate table year_week;
-- put some validation here !
if to_yr < from_yr then
leave proc_main;
end if;
-- create years and weeks...
set yr = from_yr;
while yr <= to_yr do
set wk = 1;
while wk < 53 do
insert into year_week (year_id, week_id) values (yr,wk);
set wk=wk+1;
end while;
set yr=yr+1;
end while;
end proc_main #
delimiter ;
call populate_year_week(2001,2009);
select * from year_week order by year_id, week_id;