带有previous和next元素的PHP foreach打印数组

时间:2011-11-24 10:25:23

标签: php arrays foreach next

我有一个数组$ data,我想用foreach打印它($ data as $ detail)。事情是我想在foreach内部打印上一个和下一个元素。像这样:

$data = array(1,2,3,4,5,6,7,8);

// foreach result should look like this
8,1,2
1,2,3
2,3,4
3,4,5
4,5,6
5,6,7
6,7,8
7,8,1

3 个答案:

答案 0 :(得分:5)

<?php

$data = array(1,2,3,4,5,6,7,8);
$count = count($data);

foreach($data as $index => $number)
{
  $previous = $data[($count+$index-1) % $count]; // '$count+...' avoids problems
                                                 // with modulo on negative numbers in PHP
  $current = $number;
  $next = $data[($index+1) % $count];

  echo $previous.", ".$current.", ".$next."\n";
}

关于负数的模数:http://mindspill.net/computing/cross-platform-notes/php/php-modulo-operator-returns-negative-numbers.html

答案 1 :(得分:0)

你可以去:

$data = array (1,2,3,4,5,6,7,8);
$count = count ($data);
foreach ($data as $key => $current)
{
  if (($key - 1) < 0)
  {
    $prev = $data[$count - 1];
  }
  else
  {
    $prev = $data[$key - 1];
  }

  if (($key + 1) > ($count - 1))
  {
    $next = $data[0];
  }
  else
  {
    $next = $data[$key + 1];
  }

echo $prev . ', ' . $current . ', ' . $next . "\n";

或者如果简洁是一个问题:

$count = count ($data);
foreach ($data as $i => $current)
{
  $prev = $data[(($i - 1) < 0) ? ($count - 1) : ($i - 1)];
  $next = $data[(($i + 1) > ($count - 1)) ? 0 : ($i + 1)];

  echo $prev . ',' . $current . ',' . $next . "\n";
}

答案 2 :(得分:0)

相同的结果不同:

<?php
$data = range(1,16);
$count=count($data);
$ret='';

for($i=0;$i<$count;$i++){
    $ret.=($i==0)?$data[$count-1].',':$data[$i-1].',';
    $ret.=$data[$i].',';
    $ret.=($i+1>=$count)?$data[$count-$i-1]:$data[$i+1].'<br>';
}
echo $ret;
?>
Result:
16,1,2
1,2,3
2,3,4
3,4,5
4,5,6
5,6,7
6,7,8
7,8,9
8,9,10
9,10,11
10,11,12
11,12,13
12,13,14
13,14,15
14,15,16
15,16,1