上下移动问题 - PHP


Move Questions Up and Down - PHP

对于我拥有的系统,它使用以下代码按位置顺序生成问题:

foreach ($questionnaire->questions->sortBy('position_number') as $question)

我希望能够做的是让每个问题 ID 访问上一个问题 ID 和下一个问题 ID。因此,例如,如果我在位置为 3 的问题 ID 1 上,我希望能够访问位置为 2 的问题 ID 3 和位置为 4 的问题 ID 5。

当且仅当数组是顺序数组时,以下代码应该有效:

$myArray = ($questionnaire->questions->sortBy('position_number');
foreach ($myArray as $key => $value)
{
  $keyPrev = $key - 1;
  $keyNext = $key + 1;
  echo "Next value is ".$myArray[$keyNext]."<br>";
  echo "Current value is ".$value."<br>";
    //OR
  echo "Current value is ".$myArray[$key]."<br>";
  if ($key > 0)
  echo "Previous value was ".$myArray[$keyPrev]."<br>";
}

请记住在使用$keyPrev之前检查if ($key > 0),因为在第一次迭代中,您仍将计算$keyPrev并且该$keyPrev将无效。

使用 array_keys() 获取数组的键,然后像往常一样foreach。使用计数器来帮助跟踪您使用的密钥。这甚至适用于非数字索引。

$counter = 0;
// store it so that we can access it however we like
$questions = $questionnaire->questions->sortBy('position_number');
// get an array of keys of the $questions array. They are returned in order.
$questionKeys = array_keys($questions);
// use to check that there is a next question
$countKeys = count($keys) - 2;
foreach($questions as $question) {
  // only want to access the previous question if there is a previous question
  if ($counter > 0) {
    $previousQuestion = $questions[$questionKeys[$counter - 1]];
    // do interesting things with the previous question
  }
  // only access the next question if there is a next question
  if ($counter < $countKeys) {
    $nextQuestion = $questions[$questionKeys[$counter + 1]];
    //do interesting things
  }
  $counter++;
}