在我的验证课程中,我有这个:
$fields['a_1'] = 'First Question';
$fields['a_2'] = 'Second Question';
$fields['a_3'] = 'Third Question';
$fields['a_4'] = 'Fourth Question';
这已经过时了 - 我有大约40个要编写,每个集都有匹配的验证规则:
$rules['a_1'] = 'hour';
$rules['a_2'] = 'hour';
...
有没有办法说:
$fields['a_' . 1 - 17] = "One, Two"
等等...
只是好奇......如果没有,我会蛮力。
答案 0 :(得分:1)
你可以试试这个
$ar=array("One","Two","Three");
for($i=1;$i<18;$i++){
$fields["a_".$i]=$ar[$i];
}
其中$ar
包含您要按顺序分配的值列表
答案 1 :(得分:0)
您可以使用带范围的foreach循环,如this page?
所示foreach (range(1, 17) as $i) {
$fields['a_' . $i] = "One, Two";
}
或者如果您需要引用另一个数组中的值:
$other_array = ("some", "other", "values");
foreach (range(1, count($other_array)) as $i) {
$fields['a_' . $i] = $other_array[$i+1];
}
答案 2 :(得分:0)
您可能会看到无法更改问题。 $ foo ['a_1']通常更好地写成$ foo ['a'] [1] - 这将使构造和使用它们更容易 - foreach($foo['a'] as $item) do_stuff($item);
比for($i=0; $i<$stop; $i++) do_stuff($foo['a_'.$i]);
更容易然后,您可以使用该数组将验证规则(以及任何其他关系)与项目本身一起存储:
$foo['a'] = array(array('fieldname' => 'First Question', 'rule' => 'hour'));