Php 访问数组中以前的键
我想用这段代码计算后缀表达式Php 访问数组中以前的键,php,Php,我想用这段代码计算后缀表达式 $test = array(1,2,"+",3,"+"); // this condition works $test = array(1,2,3,"+","+"); // this condition fails foreach($test as $key=>$val){ var_dump($test); if($val == "+"){ $test[$key] = $test[$key-1] + $test[$k
$test = array(1,2,"+",3,"+"); // this condition works
$test = array(1,2,3,"+","+"); // this condition fails
foreach($test as $key=>$val){
var_dump($test);
if($val == "+"){
$test[$key] = $test[$key-1] + $test[$key-2]; //uses previous keys
unset($test[$key-1]);
unset($test[$key-2]);
}
}
我正在使用上述代码,但在这种情况下我的代码失败
iteration 1
array (size=5)
0 => int 1
1 => int 2
2 => int 3
3 => string '+' (length=1)
4 => string '+' (length=1)
iteration 2
array (size=3)
0 => int 1
3 => int 5
4 => string '+' (length=1) // code fails here because key 2 is not available
有没有一种方法可以访问以前的键而不必从当前键中减去?还是在每次迭代foreach循环后重新排列键的方法 我知道如果我的条件结束,我可以通过在之后添加另一个循环来获取以前的关键点。但是我想用一种更好的方式来做,如果可能的话,
prev($array)
应该在foreach循环中完成这个技巧。
请注意,此函数会更改阵列的内部位置。使用next、prev、end和reset是更改指针的官方方法,事实上foreach内部使用它。你为什么要定义$test两次呢?让你知道代码何时工作,何时不工作。
$cnt = count($test);
for ($i = 0; $i < $cnt; $i++) {
echo "current item: " . $test[$i - 1] ."\n";
if ($i != 0) {
echo "previous item: " . $test[$i - 1]."\n";
}
}