除了第一个元素外,获取数组中的所有元素. (php) [英] Get all elements in array besides the first one.. ? (php)

查看:383
本文介绍了除了第一个元素外,获取数组中的所有元素. (php)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以指定获取数组中除第一个元素以外的所有元素?我通常使用foreach()遍历数组.

Is there a way to specify getting all but the first element in an array? I generally use foreach() to loop through my arrays.

say array(1,2,3,4,5),我只希望显示2、3、4、5并跳过1.

say array(1,2,3,4,5), i would only want 2, 3, 4 ,5 to show and for it to skip 1.

推荐答案

有多种方法可以解决此问题.

There are multiple ways of approaching this problem.

第一个解决方案是使用标志布尔值指示第一个元素,然后在您的 foreach

The first solution is to use a flag boolean to indicate the first element and proceed in your foreach

$firstElement = true;

foreach($array as $key => $val) {
  if($firstElement) {
    $firstElement = false;
  } else {
    echo "$key => $val\n";
  }
}

如果您的元素自然采用数字索引,则不需要布尔标志,只需检查键是否为0.

If your elements are naturally numerically indexed, you do not need the boolean flag, you can simply check if the key is 0.

foreach($array as $key => $val) {
  if($key === 0) continue;      

  echo "$key => $val\n";
}


第二种方法是欺骗您进入自然数值索引数组的方式(如果还没有的话).我将使用 array_keys() 来获取自然数字索引的键数组并对其进行循环.


The second way is to cheat your way into a naturally numerically indexed array if it isn't already. I will use array_keys() to get a naturally numerically indexed array of keys and loop it.

$keys = array_keys($array);

foreach($keys as $index => $key) {
  if($index === 0) continue;   

  $val = $array[$key];
  echo "$key => $val\n";
}


第三种方法是使用数组内部指针跳过第一个元素,然后使用 reset()继续循环 next() list() each() . 性能和资源方面,这是最佳选择.不过,可维护性会遭受很大的损失.


The third way is to use the array internal pointer to skip the first element and then continue in a loop by using reset(), next(), list(), and each(). Performance and resource-wise, this is the best option. Maintainability suffers greatly though.

reset($array); // Reset pointer to 0
next($array);  // Advance pointer to 1

while (list($key, $val) = each($array)) {
  echo "$key => $val\n";
}  


如果您不介意丢失数组的第一个元素,则可以 array_shift() 它.


If you don't mind losing the first element of the array, you can array_shift() it.

array_shift($array);

foreach($array as $key => $val) {
  echo "$key => $val\n";
}


您还可以 array_slice() 该数组.我还使用 count() 以便设置


You can also array_slice() the array. I'm also using count() in order to be able to set the preserve_keys parameter to true.

$sliced = array_slice($array, 1, count($array)-1, true);

foreach($sliced as $key => $val) {
  echo "$key => $val\n";
}

这篇关于除了第一个元素外,获取数组中的所有元素. (php)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆