【发布时间】:2014-08-07 12:08:50
【问题描述】:
目前,我有一个数组 r[1] 到 r[12]。
现在,我需要这样打印:
r[10] r[11] r[12]
r[7] r[8] r[9]
r[4] r[5] r[6]
r[1] r[2] r[3]
【问题讨论】:
标签: php arrays if-statement for-loop
目前,我有一个数组 r[1] 到 r[12]。
现在,我需要这样打印:
r[10] r[11] r[12]
r[7] r[8] r[9]
r[4] r[5] r[6]
r[1] r[2] r[3]
【问题讨论】:
标签: php arrays if-statement for-loop
for (int i = 0; i < 4; i++){
for(int j = 0; j < 3; j++){
print("%d", r[ 12 - (i * 3) + j]);
}
}
如果您需要任何其他数字而不是概括解决方案
for (int i = 0; i < count / interval; i++){
for(int j = 0; j < interval; j++){
print("%d", r[ count - (i * interval) + j]);
}
【讨论】:
假设你有一个包含 n 个元素的数组,并且你想将它们显示在 3 个元素的行中,你可以这样进行(在 php 中):
// this is your array, it starts with 1 and could end with n (but it must be divisible by 3)
$array = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
// check if the number of the elements is ok for the script
if (count($array) % 3) {
echo "The array must be divisible for the number of the element in a row!";
exit;
}
// for each row, from 1 to number of the elements in array...
for ($row = 1; $row <= count($array) / 3; $row++){
// ... and for each column (with a max of 3 columns)
for($column = 0; $column < 3; $column++){
// print out the last element, less current row multipled by 3 plus the number of the column (which was started with 1).
echo $array[count($array) - ($row * 3) + $column] . " ";
}
// another row is finished, move the cursor to the next line
echo "<br />";
}
【讨论】: