Question

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?

Was it helpful?

Solution

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'];

OTHER TIPS

If I understand your logic correctly, you just need to initialise your counter outside all the loops:

$i = 1;
foreach ($_orders as $order) {
    $oid = $order['id'];

Otherwise, it's re-set to 1 on every order.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top