编辑:
这是我生成数组的最新解决方案,它比以前更加数学化:
$q = 27;//number of questions
$c = 4;//number of columns
$m = $q%$c;//modulus
$step = floor($q/$c);
$arr = array();
for ($n=0; $n<$q; $n++){
$arr[] = 1 + $step*($n%$c) + ($m + $n%$c - abs($m - $n%$c))/2 + floor($n/$c);
}
输出如下:
array(1, 8, 15, 22, 2, 9, 16, 23, 3, 10, 17, 24, 4, 11, 18, 25, 5, 12, 19, 26, 6, 13, 20, 27, 7, 14, 21);
原始答案:
$q = 13;//number of questions
$c = 3;//number of columns
$mod = array_fill(0, $c, 0);
for ($i=0; $i<($q%$c); $i++){
$mod[$i] = 1;
}
$step = floor($q/$c);
$arr = array();
$cum = 0;
for ($i=0; $i<$c; $i++){
$cum += @$mod[$i-1];
$arr[] = 1 + $step*$i + $cum;
}
$next = $arr;
for ($i=1; $i<$step; $i++){
foreach ($next as $key => $value){
$next[$key]++;
}
$arr = array_merge($arr, $next);
}
for ($i=0; $i<$c; $i++){
$next[$i] = ($next[$i] + 1)*$mod[$i] ;
}
$arr = array_filter(array_merge($arr, $next));
var_dump($arr);
输出是:
array(1, 6, 10, 2, 7, 11, 3, 8, 12, 4, 9, 13, 5);
这是我生成表格的解决方案:
$q = 27;//number of questions
$c = 4;//number of columns
$cell = '<td>i</td>';
$table = '<table>';
$mod = array_fill(0, $c, 0);
for ($i=0; $i<($q%$c); $i++){
$mod[$i] = 1;
}
$step = floor($q/$c);
$arr = array();
$cum = 0;
$table .= '<tr>';
for ($i=0; $i<$c; $i++){
$cum += @$mod[$i-1];
$num = 1 + $step*$i + $cum;
$arr[] = $num;
$table .= str_replace('i', $num, $cell);
}
$table .= '</tr><tr>';
$next = $arr;
for ($i=1; $i<$step; $i++){
foreach ($next as $key => $value){
$num = ++$next[$key];
$table .= str_replace('i', $num, $cell);
}
//$arr = array_merge($arr, $next);
$table .= '</tr><tr>';
}
$table = substr($table, 0 , -4);
for ($i=0; $i<$c; $i++){
$next[$i] = ($next[$i] + 1)*$mod[$i] ;
}
$next = array_filter($next);
$span = $c - count($next);
$ini = '';
$fin = '';
$last = '';
foreach ($next as $key => $value){
$ini = '<tr>';
$last .= str_replace('i', $value, $cell);
$fin = '<td span="'.$span.'"> </td></tr>';
}
//$arr = array_merge($arr, $next);
$table .= $ini.$last.$fin.'</table>';
echo $table;
有 27 个问题和 4 列,输出为:
<table>
<tr><td>1</td><td>8</td><td>15</td><td>22</td></tr>
<tr><td>2</td><td>9</td><td>16</td><td>23</td></tr>
<tr><td>3</td><td>10</td><td>17</td><td>24</td></tr>
<tr><td>4</td><td>11</td><td>18</td><td>25</td></tr>
<tr><td>5</td><td>12</td><td>19</td><td>26</td></tr>
<tr><td>6</td><td>13</td><td>20</td><td>27</td></tr>
<tr><td>7</td><td>14</td><td>21</td><td span="1"> </td></tr>
</table>
当然,您可以修改 的值$cell
以在表格单元格中插入链接或任何您想要的内容。