对于我所拥有的系统,它使用以下代码按位置顺序生成问题:
foreach ($questionnaire->questions->sortBy('position_number') as $question)
希望我能够做的是为每个问题ID访问以前的问题ID和下一个问题ID。因此,如果我在问题id 1上有一个位置为3,我希望能够访问位置为2且问题ID为5的问题ID 3。
答案 0 :(得分:0)
IF如果数组是一个顺序数组,以下代码应该可以工作:
$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>";
}
请记住在使用if ($key > 0)
之前检查$keyPrev
,因为在第一次迭代中,您仍然要计算$ keyPrev并且$ keyPrev将无效。
答案 1 :(得分:0)
像往常一样使用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++;
}