PHP循环(一周中的每一天和每小时)

时间:2015-08-21 23:47:36

标签: php

我想创建一个循环(结果将插入到javascript中)

语法:

  • 第一个数字是当天(星期一 - 星期五/ 1 - 5)
  • 第二个数字是小时(1 - 11)

所以这最终应该返回循环:

subject_1_1: $("#subject_1_1").val(),
subject_2_1: $("#subject_2_1").val(),
subject_3_1: $("#subject_3_1").val(),
subject_4_1: $("#subject_4_1").val(),
subject_5_1: $("#subject_5_1").val(),
subject_1_2: $("#subject_1_2").val(),
subject_2_2: $("#subject_2_2").val(),
subject_3_2: $("#subject_3_2").val(),
subject_4_2: $("#subject_4_2").val(),
subject_5_2: $("#subject_5_2").val(),
subject_1_3: $("#subject_1_3").val(),

,直到

subject_5_11: $("#subject_5_11").val()

最后一个元素不应该有逗号。

2 个答案:

答案 0 :(得分:1)

// first sets x = 1, then, while x isn't equal to 5 the code
// inside `{ ... }` is executed and x is added 1
for($x=1;$x<=5;$x++){
    // again, but this time with y, from 1 to 11.
    for($y=1;$y<=11;$y++){
        // So we end up here and we now this code is going to execute
        // elevent times for each x value, and a total of 5 x values.
        // thats (x = from 1 to 5) * (y = from 1 to 11).
        // This string is printed (`echo`) every time for each iteration.
        echo "subject_1_3: $(\"#subject_".$x."_".$y."\").val()".(!($x==5&&$y==11)?",":"")."\n";
    }
}

已编辑1:现在删除最后一个逗号。

已编辑2:添加了评论,但请阅读:

在正在打印的字符串中,我注意到这段代码:

!($x==5&&$y==11)?",":""

执行以下操作:

if this is true ? this is executed : and if it is not, then this is executed

所以,在伪:

(if not (x=5 and y = 11)) then (print comma) else (don't)

答案 1 :(得分:0)

为什么不在JavaScript本身呢?

var obj, x, y;
obj = {}; // this will be the object your subject_X_Y properties belong to
for( x=1; x<=5; x++) {
    for( y=1; y<=11; y++) {
        obj['subject_'+x+'_'+y] = $('#subject_'+x+'_'+y).val();
    }
}