donglei_0507 2012-07-10 20:20
浏览 31
已采纳

修正foreach循环中的自动增量

I have a script that is looping through an array of orders with an inner loop going through all the items that were in that particular order. At the end of the script I need to concatenate a string with all the item data with an unique identifier for each. My problem arises when I get past the first order.

We will assume this loop will iterate through 3 orders. Here is my example:

foreach ($_orders as $order)
{
$oid = $order['id'];
$i = 1;
foreach ($order['items'] as $item)
         {
            $cjItemStr .= '&ITEM'. $i . '=' . $item['sku'] . '&AMT' . $i . '=' . $item['price'] . '&QTY' . $i . '=' . $item['qty'];
            $i++;
         }
}

This would correctly output what I need for 1 order. The string would read:

&ITEM1=TT-5555&AMT1=5.00&QTY1=2&ITEM2=TT-3333&AMT2=10.00&QTY2=1&ITEM3=TT-2222&AMT3=15.00&QTY3=1

This works great for one order but once I move onto the next order I need the incrementer to continue from where the other one left off. It would need to move onto ITEM4,AMT4,QTY4,ITEM5,AMT5,QTY5 etc. As it stands now it just goes back to 1. Anyone have any idea on how I could fix this?

  • 写回答

2条回答 默认 最新

  • donglin5770 2012-07-10 20:22
    关注

    Just move your initialization of $i outside the outer loop.

    // Initialize $i outside the first loop:
    $i = 1;
    foreach ($_orders as $order)
    {
      $oid = $order['id'];
      foreach ($order['items'] as $item)
      {
         $cjItemStr .= '&ITEM'. $i . '=' . $item['sku'] . '&AMT' . $i . '=' . $item['price'] . '&QTY' . $i . '=' . $item['qty'];
         // And increment $i for each order item
         $i++;
      }
    }
    // Assuming count($_orders) == 3 and each has count($order['items'] == 3)
    // $i is now 10 after all loops complete.
    

    However, if you need the value of $i to persist beyond each run of this script, you'll need to store it somewhere, such as writing it to a text file or sticking it into a database. As it is now, any time you run this script, you start back at $i = 0

    Finally, I'm not sure how Magento handles array elements, but if this query string is to be parsed by PHP, you can format it such that each element is an array. Then when received, access as $_GET['ITEM'][] for example.

     // Surrounding each with [] will allow PHP to process them as arrays in the script that receives this
     $cjItemStr .= '&ITEM['. $i . ']=' . $item['sku'] . '&AMT[' . $i . ']=' . $item['price'] . '&QTY[' . $i . ']=' . $item['qty'];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮