开发者

looking at the next element in the loop

Ok so i have this foreach php loop

<?php foreach($final_products as $product){ ?>

and I am accessing it like this

<?php print $product['product_price']; ?>

which is great but the challenge I have is how do i access the next element in the array within this array so like this

<?php print $product['product_price'] + $product["next_product"]['product_price']; ?>

next_product is just a name i have to illustrate that i need the next product in the products arrays price but still continue with the flow开发者_开发问答 of the array loop...any ideas


Consider the situation where you're at the end of the loop, and there is no "next_product"; what do you want to do then?

Probably the best situation to do is to not be looking for the next product, but store the last product you processed, and work from there. That way, you're not getting ahead of your looping process.


You could start your loop one step ahead an use a temporary variable that holds the prevous item like this:

$curr = null;
foreach ($arr as $next) {
    if (!is_null($curr)) {
        // your code
    }
    $curr = $next;
}

With this the first iteration is skipped to assign $curr so in the next iteration $curr is actually the previous item.


<?php 
  for($i=0;$i<count($final_products)-1;$i++){  
      echo $final_products[$i+1];
  }
?>

Use: $i + 1

I have added the for loop to be safe in the cast of the last element in array. Thanks @KonForce

If you need to something with the last elemnet of array yuo could use array_pop();

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜