<?php $arr = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ]; /* $arr = [ [1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16] ]; */ $ret = spiral_order($arr); echo implode(',', $ret) . PHP_EOL; function spiral_order($arr) { //存放最终数组 $spiral = []; //左边界,每遍历完,其值+1 $left = 0; //右边界,每遍历完,其值-1 $right = count($arr) - 1; //上边界,每遍历完,其值+1 $top = 0; //下边界,每遍历完,其值-1 $bottom = count($arr[0]) - 1; //横轴 $col = 0; //纵轴 $row = 0; while (true) { //遍历上边,从左向右 for ($col = $left; $col <= $right; $col++) { $spiral[] = $arr[$top][$col]; } //相当于上边的数据从矩阵里消去 if (++$top > $bottom) { break; } //遍历右边 for ($row = $top; $row <= $bottom; $row++) { $spiral[] = $arr[$row][$right]; } //相当于右边的数据从矩阵里消去 if (--$right < $left) { break; } //遍历下边 for ($col = $right; $col >= $left; $col--) { $spiral[] = $arr[$bottom][$col]; } //相当于下边的数据从矩阵里消去 if (--$bottom < $top) { break; } //遍历左边 for ($row = $bottom; $row >= $top; $row--) { $spiral[] = $arr[$row][$left]; } //相当于左边的数据从矩阵里消去 if (++$left > $right) { break; } } return $spiral; }