如何将 php 中的二维数组旋转 90 度 [英] How can I rotate a 2d array in php by 90 degrees

查看:38
本文介绍了如何将 php 中的二维数组旋转 90 度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将矩阵顺时针旋转 90 度.这相当于将输入的第一列作为输出的第一行,将输入的第二列作为输出的第二行,将输入的第三列作为输出的第三行.请注意,列的底部=行的开头,因为旋转了 90 度.

I want to rotate a matrix 90 degrees clockwise. This amounts to making the first column in the input the first row of the output, the second column of the input the 2nd row of the output, and the 3rd column of the input the 3rd row of the output. Note that the bottom of the column=the beginning of the row, because of the 90 degree rotation.

例如:

$matrix=    [[1, 2, 3]
             [4, 5, 6], 
             [7, 8, 9]];

rotate90degrees($matrix)=      [[7, 4, 1],
                                [8, 5, 2],
                                [9, 6, 3]]

我所知道的是我首先转置矩阵,然后交换列以将矩阵旋转 90 度.这如何应用于php?

What I know is I have first transpose the matrix and then swap the columns to rotate the matrix by 90 degrees. How can this be applied to php?

推荐答案

php 没有像矩阵的转置"这样的概念,而没有添加某种线性代数库.你可以通过每个矩阵和交换一些索引来本地完成

php doesn't have concepts like "transpose" for a matrix without adding some sort of linear algebra library. you can do it natively by eaching through the matrix and swapping some indexes

<?php

function rotate90($mat) {
    $height = count($mat);
    $width = count($mat[0]);
    $mat90 = array();

    for ($i = 0; $i < $width; $i++) {
        for ($j = 0; $j < $height; $j++) {
            $mat90[$height - $i - 1][$j] = $mat[$height - $j - 1][$i];
        }
    }

    return $mat90;
}

$mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
print_r($mat);
//123
//456
//789
print_r(rotate90($mat));
//741
//852
//963


$mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9], ["a", "b", "c"]];
print_r($mat);
//123
//456
//789
//abc
print_r(rotate90($mat));
//a741
//b852
//c963

这篇关于如何将 php 中的二维数组旋转 90 度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆