我有一个数组$ 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
答案 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";
}
答案 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