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

查看:79
本文介绍了如何将PHP中的2D数组旋转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中的2D数组旋转90度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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