Tracking Pixel - PHP Issue

374 Views Asked by At

How can i add a statement to this code where it stops if qty = 0.

I got this code from here but it is displaying an additional ITEM after the last one.

for example

https://www.emjcd.com/u?CID=1521607&OID=100000393&TYPE=type&ITEM1=401000305964&AMT1=16.9900&QTY1=1&ITEM2=401000305964&AMT2=0.0000&QTY2=0**&TYPE=347774&CURRENCY=USD&METHOD=IMG 

It added ITEM2=401000305964&AMT2=0.0000&QTY2=0

although the database and invoice only have one item

        <?php
            $_customerId = Mage::getSingleton('customer/session')->getCustomerId();
            $lastOrderId = Mage::getSingleton('checkout/session')->getLastOrderId();
            $order = Mage::getSingleton('sales/order'); 
            $order->load($lastOrderId);
            $_totalData =$order->getData(); 
            $_sub = $_totalData['subtotal'];//USD ==> global_currency_code,base_currency_code order_currency_code
            // Incase if it is simple do this ==> https://www.emjcd.com/u?AMOUNT= $_sub; 
            //print_r($order); print_r($_totalData);

            $_order   = $this->getOrder();
            $allitems = $order->getAllItems();
            $index    = 1;
            $cjData   = "";//Needed format ==> &ITEM1=3214sku&AMT1=13.49&QTY1=1&ITEM2=6577sku&AMT2=7.99&QTY2=2&
            foreach($allitems as $item)
            {
              $cjData.="&ITEM".$index."=".$item->getSku()."&AMT".$index."=".$item->getPrice()."&QTY".$index."=".$item->getQtyToShip();
              $index++;
            }
        ?>
        <div style="display:none;">
            <img src="https://www.emjcd.com/u?CID=1&OID=<?php echo $this->getOrderId(); ?>&TYPE=3<?php echo $cjData; ?>&CURRENCY=USD&METHOD=IMG" height="1" width="20"> 
        </div>
3

There are 3 best solutions below

0
imperium2335 On

What about break; if the qty is 0 just before you append $cjData.

1
Grant Taylor On

You could use a simple if statement, so the string is only appended if the quantity is not 0.

foreach($allitems as $item)
{
    if ($item->getQtyToShip() != 0) {
        $cjData.="&ITEM".$index."=".$item->getSku()."&AMT".$index."=".$item->getPrice()."&QTY".$index."=".$item->getQtyToShip();
    }
    $index++;
}
0
Brian Wasner On

You need to set your $index variable to zero (0) before you start the foreach loop.

When you initialize your $index variable to one (1) before you go into the foreach loop, the fact that you have a line which increments the variable by one instantly throws the total item count off by 1, because it will add (a minimum) of 1 to the value (making it 2 the first time through). This is why your value held in $index if off.