编辑代码

<?php 


function generateTable($boxes) {
    // 获取最大的 X 和 Y 坐标值
    $max_x = 0;
    $max_y = 0;
    foreach ($boxes as $box) {
        $max_x = max($max_x, $box['x'] + $box['w']);
        $max_y = max($max_y, $box['y'] + $box['h']);
    }

    // 创建空的表格
    $table = array_fill(0, $max_y, array_fill(0, $max_x, null));

    // 将盒子放入表格中
    foreach ($boxes as $box) {
        for ($y = $box['y']; $y < $box['y'] + $box['h']; $y++) {
            for ($x = $box['x']; $x < $box['x'] + $box['w']; $x++) {
                $table[$y][$x] = $box;
            }
        }
    }

    // 计算横线和竖线的位置
    $horiz_lines = array();
    $vert_lines = array();
    for ($y = 0; $y <= $max_y; $y++) {
        $prev_box = null;
        $prev_x = null;
        for ($x = 0; $x <= $max_x; $x++) {
            $box = $table[$y][$x];
            if ($box !== $prev_box) {
                if ($prev_box !== null) {
                    $vert_lines[] = array(
                        'startX' => $prev_x,
                        'startY' => $y,
                        'endX' => $x,
                        'endY' => $y,
                    );
                }
                $prev_box = $box;
                $prev_x = $x;
            }
        }
    }
    for ($x = 0; $x <= $max_x; $x++) {
        $prev_box = null;
        $prev_y = null;
        for ($y = 0; $y <= $max_y; $y++) {
            $box = $table[$y][$x];
            if ($box !== $prev_box) {
                if ($prev_box !== null) {
                    $horiz_lines[] = array(
                        'startX' => $x,
                        'startY' => $prev_y,
                        'endX' => $x,
                        'endY' => $y,
                    );
                }
                $prev_box = $box;
                $prev_y = $y;
            }
        }
    }

    // 返回横线和竖线的集合
    return array('horiz' => $horiz_lines, 'vert' => $vert_lines);
}


$boxes = [
    ['x' => 90, 'y' => 170, 'w' => 100, 'h' => 40],
    ['x' => 310, 'y' => 170, 'w' => 190, 'h' => 40],
    ['x' => 580, 'y' => 170, 'w' => 120, 'h' => 40],
    ['x' => 60, 'y' => 270, 'w' => 150, 'h' => 40],
    ['x' => 364, 'y' => 256, 'w' => 82, 'h' => 68],
    ['x' => 563, 'y' => 270, 'w' => 108, 'h' => 46],
    ['x' => 105, 'y' => 380, 'w' => 108, 'h' => 46],
    ['x' => 390, 'y' => 380, 'w' => 100, 'h' => 42],
    ['x' => 600, 'y' => 380, 'w' => 120, 'h' => 42],
];

generateTable($boxes);