这就是我们所拥有的,据我所知,这是一个复杂的数组:
<?php
// the elements array var_dump($elements);
$elements = array(4) {
[0]=> object(stdClass) { ["id"]=> string(1) "1" ["velocity"]=> string(3) "500" } //this is element0
[1]=> object(stdClass) { ["id"]=> string(1) "2" ["velocity"]=> string(3) "600" } //this is element1
[2]=> object(stdClass) { ["id"]=> string(1) "3" ["velocity"]=> string(3) "700" } //this is element2
[3]=> object(stdClass) { ["id"]=> string(1) "4" ["velocity"]=> string(3) "800" } //this is element3
}
// the foreach
$sumAll=0;
foreach ($elements as $key=>$element) {
$trek = $element->velocity;
$someVarINeed = ( $key == 0 ) ? $external_value : $sumAll + $trek[$key-1]; // this is what I know it would work but it does not
// EXPECTED RESULTS
//because there is no previous
when $key=0 $someVarINeed = $external_value;
// this should be $someVarINeed = 0 + 500 = 500
when $key=1 $someVarINeed = $sumAll + $element0->velocity;
// this should be $someVarINeed = 0 + 500 + 600 = 1100
when $key=2 $someVarINeed = $sumAll + $element0->velocity + $element1->velocity;
// this should be $someVarINeed = 0 + 500 + 600 + 700 = 1800
when $key=3 $someVarINeed = $sumAll + $element0->velocity + $element1->velocity + $element2->velocity;
}
?>
我编辑了我希望更有意义的代码。
我不知道这是否是一个对象/数组,我想将要用于每个 $element 的 $trek 的值总结为一个仅由先前元素值的总和而不是其本身确定的值。
一如既往,感谢您的回复:)