php for 下一个,从PHP的下一个foreach项中拉出元素?

本文介绍在PHP中如何高效地遍历数组并计算相邻元素之间的百分比差异,提供了多种方法包括使用foreach循环、for循环及数组迭代器函数等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

8 个答案:

答案 0 :(得分:10)

以其他方式执行,并存储上一个条目并进行比较。

$prev = null;

foreach ($item as $i){

if ($prev !== null){

diff($prev, $i);

}

$prev = $i

}

答案 1 :(得分:4)

简单回答:不要使用foreach循环。请改用简单的for循环:

for ($i = 0; $i < count($array); $i++) {

if (isset($array[$i + 1])) {

$thisValue = $array[$i]['value'];

$nextValue = $array[$i + 1]['value'];

$percentageDiff = ($nextValue-$thisValue)/$thisValue;

}

}

答案 2 :(得分:1)

你应该可以使用:

foreach($array as $a)

{

$array_copy = $array;

$thisValue = $a['value'];

$nextValue = next($array_copy);

$nextValue = $nextValue['value'];

$percentageDiff = ($nextValue-$thisValue)/$thisValue;

}

这将复制数组,然后将指针移动1。

答案 3 :(得分:1)

最简单的解决方案IMO就是改变你的心态。而不是检查当前和下一个记录,检查先前和当前记录。记住前一个比获得下一个更容易。

如果你不想那样,你也可以放弃foreach并使用for迭代C风格和一个计数器变量 - 虽然有一个漏洞:PHP的稀疏数组可以咬你,所以你在迭代之前,最好在被检查数组上调用array_values()。

答案 4 :(得分:1)

如果您想使用foreach,可以将当前值与之前的值进行比较,而不是使用下一个值:

$previous = null;

foreach ($array as $a) {

if (!is_null($previous)) {

$thisValue = $previous['value'];

$nextValue = $a['value'];

$percentageDiff = ($nextValue-$thisValue)/$thisValue;

}

$previous = $a;

}

通过这个你只需将整个迭代移动一个项目。

答案 5 :(得分:1)

为什么不使用普通的for循环而不是foreach迭代器?

$testArray = array(10,20,30,40,50,60,70,80,90,100);

$elementCount = count($testArray);

for($loop=0; $loop

$thisValue = $testArray[$loop];

// Check if there *is* a next element.

$nextValue = $loop + 1 < $elementCount ? $testArray[$loop + 1] : null;

// Calculate the percentage difference if we have a next value.

if($nextValue) $percentageDiff = ($nextValue-$thisValue)/$thisValue;

}

?>

答案 6 :(得分:1)

'使用之前的值通常比下一个更容易:

$lastValue = NULL;

foreach ($array as $a) {

if ($lastValue === NULL) {

$lastValue = $a['value'];

continue;

}

$percentageDiff = ($a['value'] - $lastValue) / $lastValue;

$lastValue = $a['value'];

}

答案 7 :(得分:1)

for($i=0;$i

$thisValue = $array[$i];

$nextValue = $array[i+1]; // will not be set if $i==count($array)-1

$percentageDiff = ($nextValue-$thisValue)/$thisValue;

}

确实有array iterator个函数可以支持你需要的东西,而且简单地用next()/ prev()等循环遍历数组也可以正常工作但上面的解决方案更优雅

它不能与foreach一起使用,因为foreach创建了一个引用的副本,并且没有在数组本身中设置数组指针。

这是一个可以使用数组迭代器函数用于关联数组的示例:

$arrayobject = new ArrayObject($array);

$iterator = $arrayobject->getIterator();

for($i=0;$i

$iterator->seek($i);

$thisValue = $iterator->current();

$iterator->seek($i+1);

$nextValue = $iterator->current();

$percentageDiff = ($nextValue-$thisValue)/$thisValue;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值