在foreach中获取以前的数组值

时间:2010-11-10 19:57:26

标签: php arrays

我的阵列:

$arr = array("jan","feb","mar","apr","mei","jun","jul","agu","sep","okt","nov","des");
然后我做了一个foreach

foreach($arr as $ar){
  echo $ar;
}

将jan输出到des

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

例如,当我到达feb时,我也想显示jan,当我到jul时,我想要显示jun等。

7 个答案:

答案 0 :(得分:37)

$previousValue = null;
foreach($arr as $ar){
  echo $ar;
  if($previousValue) {
    echo $previousValue;
  }
  $previousValue = $ar;
}

答案 1 :(得分:6)

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

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

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

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

答案 2 :(得分:1)

reset($array);
while($val=current($array))
{
    var_dump($val); // current
    var_dump(prev($array)); // previous
    next($array); // back to current
    next($array); // next
}

答案 3 :(得分:1)

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 />';
    }
}

答案 4 :(得分:0)

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

答案 5 :(得分:0)

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

请参阅此问题并answer

答案 6 :(得分:0)

更动态

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