随机逻辑以下列模式打印数字

时间:2014-08-07 12:08:50

标签: 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]

2 个答案:

答案 0 :(得分:1)

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]);
   }

答案 1 :(得分:0)

假设您有一个包含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 />";

}