通过Foreach循环迭代

时间:2011-07-26 22:13:30

标签: php for-loop foreach iteration

我想在这个foreach中迭代一个数字做'item_name _'之类的事情。 $ i ...但我无法解决该怎么做?你能帮我个忙吗?

  $cart = $this->cart->contents();
  foreach ($cart as $item){
      $this->paypal_lib->add_field('item_name_1', $item['name']);
      $this->paypal_lib->add_field('amount_1', $item['subtotal']);
      $this->paypal_lib->add_field('item_number_1', $item['id']);
      $this->paypal_lib->add_field('quantity_1', '1');
  }

1 个答案:

答案 0 :(得分:7)

  // initialise variable:
  $i = 0;

  $cart = $this->cart->contents();
  foreach ($cart as $item){
      $i++;
      // do what you want with the counter variable '$i'.

      $this->paypal_lib->add_field("item_name_$i", $item['name']);
      $this->paypal_lib->add_field("amount_$i", $item['subtotal']);
      $this->paypal_lib->add_field("item_number_$i", $item['id']);
      $this->paypal_lib->add_field("quantity_$i", '1');
  }