是否有一种优雅的方式从第二个索引开始foreach然后做其余的事情?

时间:2015-02-23 19:43:25

标签: php arrays foreach

如果我有以下内容:

$a = array(
    "one" => 1,
    "two" => 2,
    "three" => 3,
    "seventeen" => 17
);

foreach ($a as $v) {
    echo $v;
}

如何输出:

2, 1, 3, 17

3 个答案:

答案 0 :(得分:2)

引用PHP Manual on Language Operators

  

+运算符返回附加到左侧的右侧数组   阵列;对于存在于两个数组中的键,来自的数组   将使用左手数组,以及来自的匹配元素   右手阵列将被忽略。

$a = array(
    "one" => 1,
    "two" => 2,
    "three" => 3,
    "seventeen" => 17
);

$b = array_values($a);
echo implode(', ', array($b[1], $b[0]) + $b), PHP_EOL;

输出:

2, 1, 3, 17

答案 1 :(得分:1)

$values = array_values($a);
echo "{$values[1]}, {$values[0]}, "
foreach (array_slice($values, 2) as $v){
    echo "$v, "
}

如果你关心最后一个逗号......

$values = array_values($a);
echo "{$values[1]}, {$values[0]}, "
$lastIndex = count($values) - 1;

foreach (array_slice($values, 2) as $k => $v){
    echo $v;
    if ($k != $lastIndex){
        echo ", ";
    }
}

答案 2 :(得分:0)

您可以执行以下操作:

<?php

$my_array = array(...); 

$keys = array_keys($my_array);
$second_key = $keys[1]; // if your array can be whatever size, probably want to check that first

echo $my_array[$second_key];

foreach ($my_array as $key => $value) {
  if ($key == $second_key) {
    continue;
  }

  echo $value;
}

?>