Home >Backend Development >PHP Problem >How to implement matrix in php code

How to implement matrix in php code

藏色散人
藏色散人Original
2021-03-17 09:49:552929browse

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;j01390daae83d4e898fc13922a1f57227=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]

<?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);

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn