php循环取值返回,php-在foreach循环中获取下一个元素

php-在foreach循环中获取下一个元素

我有一个foreach循环,我想看看循环中是否存在下一个元素,以便可以将当前元素与下一个元素进行比较。 我怎样才能做到这一点? 我已经阅读了有关当前功能和下一个功能的信息,但我不知道如何使用它们。

提前致谢

chchrist asked 2020-07-17T11:42:38Z

9个解决方案

34 votes

一种独特的方法是反转阵列然后循环。 这同样适用于非数字索引数组:

$items = array(

'one' => 'two',

'two' => 'two',

'three' => 'three'

);

$backwards = array_reverse($items);

$last_item = NULL;

foreach ($backwards as $current_item) {

if ($last_item === $current_item) {

// they match

}

$last_item = $current_item;

}

如果您仍然对使用$i < $length - 1;和$length = count($items) - 1;函数感兴趣,则可以执行以下操作:

$items = array('two', 'two', 'three');

$length = count($items);

for($i = 0; $i < $length - 1; ++$i) {

if (current($items) === next($items)) {

// they match

}

}

#2可能是最好的解决方案。 请注意,比较阵列中的最后两项后,$i < $length - 1;将停止循环。 我将其放在循环中,以使示例更加明确。 您可能应该只计算$length = count($items) - 1;

Stephen answered 2020-07-17T11:42:57Z

20 votes

您可能使用while循环而不是foreach:

while ($current = current($array) )

{

$next = next($array);

if (false !== $next && $next == $current)

{

//do something with $current

}

}

pronskiy answered 2020-07-17T11:43:17Z

11 votes

正如php.net/foreach指出的那样:

除非引用了数组,否则foreach将在指定数组的副本上而不是数组本身上进行操作。 foreach对数组指针有一些副作用。 不要在foreach期间或之后依赖数组指针而不重置它。

换句话说-做您要做的事情不是一个好主意。 与某人讨论您为何要尝试这样做的好主意,看看是否有更好的解决方案? 如果没有其他可用资源,请随时在irc.freenode.net上的## PHP中询问我们。

TML answered 2020-07-17T11:43:46Z

8 votes

如果索引是连续的:

foreach ($arr as $key => $val) {

if (isset($arr[$key+1])) {

echo $arr[$key+1]; // next element

} else {

// end of array reached

}

}

Mārtiņš Briedis answered 2020-07-17T11:44:06Z

5 votes

如果其数字索引为:

foreach ($foo as $key=>$var){

if($var==$foo[$key+1]){

echo 'current and next var are the same';

}

}

Rob answered 2020-07-17T11:44:26Z

3 votes

通用解决方案可以是缓存迭代器。 正确实现的缓存迭代器可与任何迭代器一起使用,并节省内存。 PHP SPL具有CachingIterator,但非常奇怪,并且功能非常有限。 但是,您可以这样编写自己的超前迭代器:

class NeighborIterator implements Iterator

{

protected $oInnerIterator;

protected $hasPrevious = false;

protected $previous = null;

protected $previousKey = null;

protected $hasCurrent = false;

protected $current = null;

protected $currentKey = null;

protected $hasNext = false;

protected $next = null;

protected $nextKey = null;

public function __construct(Iterator $oInnerIterator)

{

$this->oInnerIterator = $oInnerIterator;

}

public function current()

{

return $this->current;

}

public function key()

{

return $this->currentKey;

}

public function next()

{

if ($this->hasCurrent) {

$this->hasPrevious = true;

$this->previous = $this->current;

$this->previousKey = $this->currentKey;

$this->hasCurrent = $this->hasNext;

$this->current = $this->next;

$this->currentKey = $this->nextKey;

if ($this->hasNext) {

$this->oInnerIterator->next();

$this->hasNext = $this->oInnerIterator->valid();

if ($this->hasNext) {

$this->next = $this->oInnerIterator->current();

$this->nextKey = $this->oInnerIterator->key();

} else {

$this->next = null;

$this->nextKey = null;

}

}

}

}

public function rewind()

{

$this->hasPrevious = false;

$this->previous = null;

$this->previousKey = null;

$this->oInnerIterator->rewind();

$this->hasCurrent = $this->oInnerIterator->valid();

if ($this->hasCurrent) {

$this->current = $this->oInnerIterator->current();

$this->currentKey = $this->oInnerIterator->key();

$this->oInnerIterator->next();

$this->hasNext = $this->oInnerIterator->valid();

if ($this->hasNext) {

$this->next = $this->oInnerIterator->current();

$this->nextKey = $this->oInnerIterator->key();

} else {

$this->next = null;

$this->nextKey = null;

}

} else {

$this->current = null;

$this->currentKey = null;

$this->hasNext = false;

$this->next = null;

$this->nextKey = null;

}

}

public function valid()

{

return $this->hasCurrent;

}

public function hasNext()

{

return $this->hasNext;

}

public function getNext()

{

return $this->next;

}

public function getNextKey()

{

return $this->nextKey;

}

public function hasPrevious()

{

return $this->hasPrevious;

}

public function getPrevious()

{

return $this->previous;

}

public function getPreviousKey()

{

return $this->previousKey;

}

}

header("Content-type: text/plain; charset=utf-8");

$arr = [

"a" => "alma",

"b" => "banan",

"c" => "cseresznye",

"d" => "dio",

"e" => "eper",

];

$oNeighborIterator = new NeighborIterator(new ArrayIterator($arr));

foreach ($oNeighborIterator as $key => $value) {

// you can get previous and next values:

if (!$oNeighborIterator->hasPrevious()) {

echo "{FIRST}\n";

}

echo $oNeighborIterator->getPreviousKey() . " => " . $oNeighborIterator->getPrevious() . " -----> ";

echo "[ " . $key . " => " . $value . " ] -----> ";

echo $oNeighborIterator->getNextKey() . " => " . $oNeighborIterator->getNext() . "\n";

if (!$oNeighborIterator->hasNext()) {

echo "{LAST}\n";

}

}

Dávid Horváth answered 2020-07-17T11:44:46Z

2 votes

您可以在foreach之前获取数组的键,然后使用计数器检查下一个元素,例如:

//$arr is the array you wish to cycle through

$keys = array_keys($arr);

$num_keys = count($keys);

$i = 1;

foreach ($arr as $a)

{

if ($i < $num_keys && $arr[$keys[$i]] == $a)

{

// we have a match

}

$i++;

}

这对于简单的数组(例如array(1,2,3))和键控数组(例如array('first'=>1, 'second'=>2, 'thrid'=>3))均适用。

eclipse31 answered 2020-07-17T11:45:11Z

1 votes

php中的foreach循环将遍历原始数组的副本,从而使index + 1和array_key_exists()函数无效。 如果您有关联数组并需要获取下一个项目,则可以遍历数组键:

foreach (array_keys($items) as $index => $key) {

// first, get current item

$item = $items[$key];

// now get next item in array

$next = $items[array_keys($items)[$index + 1]];

}

由于生成的键数组本身具有连续索引,因此可以使用该索引来访问原始数组。

请注意,对于最后一次迭代,index + 1将为array_key_exists(),因为在最后一次迭代之后没有下一个项目。 访问不存在的数组键将抛出php通知。 为避免这种情况,请执行以下任一操作:

在将值分配给index + 1之前检查最后一次迭代

检查带有index + 1的密钥是否与array_key_exists()存在

使用方法2,完整的foreach可能如下所示:

foreach (array_keys($items) as $index => $key) {

// first, get current item

$item = $items[$key];

// now get next item in array

$next = null;

if (array_key_exists($index + 1, array_keys($items))) {

$next = $items[array_keys($items)[$index + 1]];

}

}

Liquinaut answered 2020-07-17T11:45:54Z

1 votes

您可以获得键/值和索引

$a = array(

'key1'=>'value1',

'key2'=>'value2',

'key3'=>'value3',

'key4'=>'value4',

'key5'=>'value5'

);

$keys = array_keys($a);

foreach(array_keys($keys) as $index ){

$current_key = current($keys); // or $current_key = $keys[$index];

$current_value = $a[$current_key]; // or $current_value = $a[$keys[$index]];

$next_key = next($keys);

$next_value = $a[$next_key] ?? null; // for php version >= 7.0

echo "{$index}: current = ({$current_key} => {$current_value}); next = ({$next_key} => {$next_value})\n";

}

结果:

0: current = (key1 => value1); next = (key2 => value2)

1: current = (key2 => value2); next = (key3 => value3)

2: current = (key3 => value3); next = (key4 => value4)

3: current = (key4 => value4); next = (key5 => value5)

4: current = (key5 => value5); next = ( => )

Andrei Krasutski answered 2020-07-17T11:46:18Z

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值