So this might be quite bizarre, but... Imagine a grid of 10x10, each numbered left to right, top to down, starting at 1 and ending in 100.
I want to input a grid number ($plot
) and get each grid number that surrounds it.
I started by making an array:
$plot = 45;
$arr = array(
$plot-11, $plot-10, $plot-9,
$plot-1, $plot, $plot+1,
$plot+9, $plot+10, $plot+11
);
This works fine.
Except if I add a plot near the edge of the grid (like $plot = 50
) it would give me results at the start of the next row. Eg:
Any clever ways to solve this?
答案 0 :(得分:0)
您可以过滤数组并仅保留距离为1或0的单元格:
$plot = 50;
$arr = array(
$plot-11, $plot-10, $plot-9,
$plot-1, $plot, $plot+1,
$plot+9, $plot+10, $plot+11
);
$plotX = ($plot - 1) % 10 + 1;
$plotY = ceil($plot / 10);
$arr = array_filter($arr, function($item) use($plotX, $plotY){
return 1 >= abs($plotX - (($item - 1) % 10 + 1))
&& 1 >= abs($plotY - ceil($item / 10));
});
var_export($arr);
结果:
array (
0 => 39,
1 => 40,
3 => 49,
4 => 50,
6 => 59,
7 => 60,
)