The method of implementing the matrix in php code: first take out the number of rows and columns; then control the number of turns in the outer loop; then pass "j=i;j
The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer
[PHP] Algorithm - Print clockwise PHP implementation of matrix
1. Take out the number of rows and columns, row, col, and the number of circles are (smaller value -1)/2 1
2. Outer loop Control the number of circles, the inner four for loops, i
3. The first for loop, from left to right, j=i;j 4. The second for loop, from top to bottom, k=i 1;k 5. The third loop, from right to left, m=col-2-i;m>=i&&row-1-i!=i;m-- arr[row-1-i][m]// When row-1-i!=i is a single row, it is only printed once 6. The fourth loop, from bottom to top, n=row-2-i;n>=i&&col-1-i!= i;n-- arr[n][i] Recommended learning: "PHP Video Tutorial" The above is the detailed content of How to implement matrix in php code. For more information, please follow other related articles on the PHP Chinese website!<?php
$arr=array();
$flag=0;
for($i=0;$i<2;$i++){
$flag=$i*2;
for($j=0;$j<2;$j++){
$flag++;
$arr[$i][]=$flag;
}
}
var_dump($arr);
//顺时针打印矩阵
function printMatrix($arr){
$res=array();
$row=count($arr);
$col=count($arr[0]);
$circle=intval((($row>$col ? $col : $row)-1)/2+1);
for($i=0;$i<$circle;$i++){
//转圈开始
//从左到右
for($j=$i;$j<=$col-1;$j++){
$t=$arr[$i][$j];
if(in_array($t,$res)) continue;
$res[]=$t;
}
//从上到下
for($k=$i+1;$k<$row-$i;$k++){
$t=$arr[$k][$col-$i-1];
if(in_array($t,$res)) continue;
$res[]=$t;
}
//从右到左
for($m=$col-$i-2;$m>=$i;$m--){
$t=$arr[$row-$i-1][$m];
if(in_array($t,$res)) continue;
$res[]=$t;
}
//从下到上
for($n=$row-$i-2;$n>$i;$n--){
$t=$arr[$n][$i];
if(in_array($t,$res)) continue;
$res[]=$t;
}
}
return $res;
}
$res=printMatrix($arr);