How to implement diagonal reversal of a two-dimensional array in PHP?
You can achieve the diagonal reversal of a PHP 2D array with the following code.
function diagonalReverse($arr) {
// 获取二维数组的行数和列数
$rows = count($arr);
$cols = count($arr[0]);
// 创建一个新的二维数组用于存放对角线反转后的结果
$result = array_fill(0, $cols, array_fill(0, $rows, 0));
// 遍历原二维数组,将元素按照对角线反转的规则放入新的二维数组中
for ($i = 0; $i < $rows; $i++) {
for ($j = 0; $j < $cols; $j++) {
$result[$j][$i] = $arr[$i][$j];
}
}
return $result;
}
// 测试
$arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
$result = diagonalReverse($arr);
foreach ($result as $row) {
echo implode(' ', $row) . PHP_EOL;
}
The code above achieves a diagonal flip by performing the operation on the input 2D array and then outputs the result.