PHP 需要帮助按方向查找某个索引,

所以,我有一个索引。0-等。我想通过一个方向获得某个索引号。


我在前端显示的内容是这样的:


0123

4567

89

如果我在0,我想下降。我怎么知道它是什么索引?


我不知道该怎么做。


编辑:我有一个包含 4 个索引(0-3)的索引列表。我有无限数量的列(意味着列数会改变。)


蛊毒传说
浏览 88回答 1
1回答

慕的地8271018

将索引加载到二维数组中,以便可以通过提供 y(上/下)和 x(左/右)来访问每个元素这就是我们的矩阵:array(3) {&nbsp; [0]=>&nbsp; array(4) {&nbsp; &nbsp; [0]=>&nbsp; &nbsp; string(1) "0"&nbsp; &nbsp; [1]=>&nbsp; &nbsp; string(1) "1"&nbsp; &nbsp; [2]=>&nbsp; &nbsp; string(1) "2"&nbsp; &nbsp; [3]=>&nbsp; &nbsp; string(1) "3"&nbsp; }&nbsp; [1]=>&nbsp; array(4) {&nbsp; &nbsp; [0]=>&nbsp; &nbsp; string(1) "4"&nbsp; &nbsp; [1]=>&nbsp; &nbsp; string(1) "5"&nbsp; &nbsp; [2]=>&nbsp; &nbsp; string(1) "6"&nbsp; &nbsp; [3]=>&nbsp; &nbsp; string(1) "7"&nbsp; }&nbsp; [2]=>&nbsp; array(2) {&nbsp; &nbsp; [0]=>&nbsp; &nbsp; string(1) "8"&nbsp; &nbsp; [1]=>&nbsp; &nbsp; string(1) "9"&nbsp; }}所以我们的'0'是$matrix[0][0],1是$matrix[0,1],4是$matrix[1, 0]等等。现在我们可以通过$y和$x访问每个元素并得到通过添加 $y(向下加 1,向上加 -1)或 $x(向右加 1,向左加 -1)来将元素按所需方向移动。如果超出索引范围,则意味着索引不存在(例如从 0 向左)。<?php$index = '0123456789';$indexArray = str_split($index);$matrix = array_chunk($indexArray, 4);function move(array $matrix, string $current, string $direction) {&nbsp; foreach ($matrix as $y => $row) {&nbsp; &nbsp; foreach ($row as $x =>&nbsp; $column) {&nbsp; &nbsp; &nbsp; if ($column === $current) {&nbsp; &nbsp; &nbsp; &nbsp; $position = [$y, $x];&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; }&nbsp; if ($direction === 'up') {&nbsp; &nbsp; $vector = [-1,0];&nbsp; } elseif ($direction === 'down') {&nbsp; &nbsp; $vector = [1,0];&nbsp; } elseif ($direction === 'right') {&nbsp; &nbsp; $vector = [0,1];&nbsp; } elseif ($direction === 'left') {&nbsp; &nbsp; $vector = [0,-1];&nbsp; }&nbsp; return $matrix[$position[0] + $vector[0]][$position[1] + $vector[1]] ?? null;}var_dump(move($matrix, '0', 'down')); // 4var_dump(move($matrix, '0', 'up')); // nullvar_dump(move($matrix, '0', 'left')); // nullvar_dump(move($matrix, '0', 'right')); // 1var_dump(move($matrix, '6', 'down')); // nullvar_dump(move($matrix, '6', 'up')); // 2var_dump(move($matrix, '6', 'left')); // 5var_dump(move($matrix, '6', 'right')); // 7
打开App,查看更多内容
随时随地看视频慕课网APP