PHP foreach print array with previous and next ele

2019-05-29 19:54发布

I have an array $data and I want to print it with foreach ($data as $detail). Thing is that I want inside foreach to print previous and next element. Something like this:

$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条回答
放荡不羁爱自由
2楼-- · 2019-05-29 20:22

Same result done differently:

<?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
查看更多
再贱就再见
3楼-- · 2019-05-29 20:23

You could go:

$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";

Or if brevity is an issue:

$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";
}
查看更多
劫难
4楼-- · 2019-05-29 20:33
<?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";
}

About modulo on negative numbers: http://mindspill.net/computing/cross-platform-notes/php/php-modulo-operator-returns-negative-numbers.html

查看更多
登录 后发表回答