为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
蛊毒传说 2023-08-26 10:20:05
所以,我有一个索引。0-等。我想通过一个方向获得某个索引号。我在前端显示的内容是这样的:0123456789如果我在0,我想下降。我怎么知道它是什么索引?我不知道该怎么做。编辑:我有一个包含 4 个索引(0-3)的索引列表。我有无限数量的列(意味着列数会改变。)
查看完整描述

1 回答

?
慕的地8271018

TA贡献1796条经验 获得超4个赞

将索引加载到二维数组中,以便可以通过提供 y(上/下)和 x(左/右)来访问每个元素


这就是我们的矩阵:


array(3) {

  [0]=>

  array(4) {

    [0]=>

    string(1) "0"

    [1]=>

    string(1) "1"

    [2]=>

    string(1) "2"

    [3]=>

    string(1) "3"

  }

  [1]=>

  array(4) {

    [0]=>

    string(1) "4"

    [1]=>

    string(1) "5"

    [2]=>

    string(1) "6"

    [3]=>

    string(1) "7"

  }

  [2]=>

  array(2) {

    [0]=>

    string(1) "8"

    [1]=>

    string(1) "9"

  }

}

所以我们的'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) {

  foreach ($matrix as $y => $row) {

    foreach ($row as $x =>  $column) {

      if ($column === $current) {

        $position = [$y, $x];

      }

    }

  }


  if ($direction === 'up') {

    $vector = [-1,0];

  } elseif ($direction === 'down') {

    $vector = [1,0];

  } elseif ($direction === 'right') {

    $vector = [0,1];

  } elseif ($direction === 'left') {

    $vector = [0,-1];

  }


  return $matrix[$position[0] + $vector[0]][$position[1] + $vector[1]] ?? null;

}


var_dump(move($matrix, '0', 'down')); // 4

var_dump(move($matrix, '0', 'up')); // null

var_dump(move($matrix, '0', 'left')); // null

var_dump(move($matrix, '0', 'right')); // 1


var_dump(move($matrix, '6', 'down')); // null

var_dump(move($matrix, '6', 'up')); // 2

var_dump(move($matrix, '6', 'left')); // 5

var_dump(move($matrix, '6', 'right')); // 7


查看完整回答
反对 回复 2023-08-26
  • 1 回答
  • 0 关注
  • 66 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信