【问题标题】:Iterating through a Foreach loop遍历 Foreach 循环
【发布时间】:2011-07-26 22:13:29
【问题描述】:

我想在这个 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');
  }

【问题讨论】:

  • 你的问题有点不清楚。你的意思是只有一个简单的计数器吗?
  • @will。是的,这是一个简单的计数器,我可以添加到字段名称中。对不起,我是菜鸟。

标签: php for-loop foreach iteration


【解决方案1】:
  // 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');
  }

【讨论】:

    猜你喜欢
    • 2013-12-16
    • 2013-03-17
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    • 2015-10-13
    • 2010-10-24
    • 1970-01-01
    相关资源
    最近更新 更多