通过Foreach循环迭代

jhu*_*hui 0 php iteration foreach for-loop

我想在这个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');
  }
Run Code Online (Sandbox Code Playgroud)

Dav*_*mas 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');
  }
Run Code Online (Sandbox Code Playgroud)