01 02 03 04
12 13 14 05
11 16 15 06
10 09 08 07
打印如上顺序的矩阵代码

<?php
function sort_matrix($n){
$start_row = 0; $start_col = 0; $end_row = $n - 1; $end_col = $n - 1;
$row = 0; $col = 0; $type = 1;
$matrix_arr = [];

for($k = 1; $k <= $n * $n; ++$k){ $matrix_arr[$row][$col] = $k; if($type == 1){//第一行 ++$col; }elseif($type == 2){//最后一列 ++$row; }elseif($type == 3){//最后一行 --$col; }elseif($type == 4){//第一列 --$row; } if($type == 1 && $col > $end_col){//遍历未赋值的首行后开始行变量+1 ++$start_row; $row = $start_row; $col = $end_col; $type = 2;//随后处理最后一列 }elseif($type == 2 && $row > $end_row){//遍历最后一列后 --$end_col; $row = $end_row; $col = $end_col; $type = 3;//随后处理最后一行 }elseif($type == 3 && $col < $start_col){//遍历最后一行后 --$end_row; $row = $end_row; $col = $start_col; $type = 4;//随后处理第一列 }elseif($type == 4 && $row < $start_row){//遍历第一列后 ++$start_col; $row = $start_row; $col = $start_col; $type = 1;//随后处理第一行 } } return $matrix_arr;}//打印row行,col列矩阵function print_matrix($matrix_arr, $row, $col){ for($i = 0; $i < $row; ++$i){ for($j = 0; $j < $col; ++$j){ echo sprintf("%02d", $matrix_arr[$i][$j]) . " "; } echo "<br />"; } }$n = 4;$matrix_arr = sort_matrix($n);print_matrix($matrix_arr, $n, $n);

?>