关于php:在foreach中获取以前的数组值

get previous array values in foreach

我的阵列:

1
$arr = array("jan","feb","mar","apr","mei","jun","jul","agu","sep","okt","nov","des");

然后我做前臂

1
2
3
foreach($arr as $ar){
  echo $ar;
}

将输出jan到des

我的问题是如何在当前键中显示以前的值?

例如,当我到达2月时,我也想显示1月,当我到达7月时,我想显示6月,等等。


1
2
3
4
5
6
7
8
$previousValue = null;
foreach($arr as $ar){
  echo $ar;
  if($previousValue) {
    echo $previousValue;
  }
  $previousValue = $ar;
}


您可以使用这些键来获取上一个键。

1
2
3
4
foreach($arr as $key => $ar){
    $prev = $arr[$key-1];
    echo "previous value -" .$prev;
}

还有prev()作为内部数组指针:

1
2
3
4
5
6
$transport = array('foot', 'bike', 'car', 'plane');
$mode = current($transport); // $mode = 'foot';
$mode = next($transport);    // $mode = 'bike';
$mode = next($transport);    // $mode = 'car';
$mode = prev($transport);    // $mode = 'bike';
$mode = end($transport);     // $mode = 'plane';


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
foreach ($arr as $key => $ar) {
    //check we aren't on jan (otherwise we get $key = -1 which doesn't work)
    if ($key != 0) {
        //print previous month followed by current month
        echo $arr[$key - 1] . '-' . $ar . '<br />';
    }
}

//OR, if you want to be able to roll through years then:

$last_key = end(array_keys($arr));
foreach ($arr as $key => $ar) {
    //check we aren't on jan
    if ($key != 0) {
        //print previous month followed by current month
        echo $arr[$key - 1] . ' - ' . $ar . '<br />';
    } else {
        echo $arr[$last_key] . ' - ' . $ar . '<br />';
    }
}


1
2
3
4
5
6
7
8
reset($array);
while($val=current($array))
{
    var_dump($val); // current
    var_dump(prev($array)); // previous
    next($array); // back to current
    next($array); // next
}

有点活力

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
$arr  = array(
   "jan",
   "feb",
   "mar",
   "apr",
   "mei",
   "jun",
   "jul",
   "agu",
   "sep",
   "okt",
   "nov",
   "des"
);
$arr2 = $arr;
foreach ($arr as $k => $currVal) {
    unset($arr2[$k]);
    foreach ($arr2 as $k => $v) {
        $nextVal = $v;

        break;
    }
    echo"next val:" . $nextVal;
    echo"current val:" . $currVal;
}

1
2
3
4
5
6
foreach($arr as $key => $value){
  if ($key > 0) {
   echo $arr[$key-1];
  }
  echo $value;
}

看看这个问题和答案。


1
2
3
4
5
6
for ( $i = 0; $i <count($arr); $i++) {
    echo $arr[$i]
    if($i > 0){
     echo $arr[$i-1]
   }
}