Tracking Pixel - PHP Issue - php

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>

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.

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

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++;
}

Related

How to get the value of a $total before the code calculated?

I want to show a content of variable whom been calculate in a foreach loop. The problem is that I want to echo it before the loop.
<?php
echo $total; // note this line I want to appear the total count of loop. the problem is it cannot appear because it is in the above of foreach loop. I want to appear it in this above before foreach loop.
$total = 0;
foreach($pathList as $item) {
$fileInfo = pathinfo($item);
if(preg_match(strtolower('/\b'.$_POST['song'].'\b/'), strtolower($filename))) {
$total = $total + 1; // the total count of foreach loop I want to appear in echo $total
}
// some code
}
?>
I do want to echo it inside the loop but only once after completed the loop.
Any idea how do I solve this problem? I tried global $total but not working...
Thanks in advance!
Generally - NO. You cannot echo variable that not been calculate yet (synchronization in PHP).
If all you do in the for-loop regarding $total is increasing by 1 then you actually count the number of element in the array so you can just do:
echo count($pathList);
Before the for-loop. Documentation in here
Updated:
If $total is affected in the loop (as you updated the question) then I believe best practice will be to counting array element first (without executing any more code), then echo the $total, afterward, loop on the original data and execute the rest of your code.
$total = 0;
foreach($pathList as $item) {
$fileInfo = pathinfo($item);
if(preg_match(strtolower('/\b'.$_POST['song'].'\b/'), strtolower($filename))) // or what ever condition you have to check for total
$total = $total + 1;
}
echo count($total); // give you the count you need
foreach($pathList as $item) {
// exec the rest of your code
}
This may run at O(2*n) but its not worse
It is not possible. Lines are executed in the order in which they appear in the script.
The value of $total at the end of the loop is equal to the value of count($pathList)
If you need the value of the last iterated element of the $pathList before the execution of the loop, then it can be echoed as
echo $pathList[count($pathList)-1];

Get First And Last Data From conditioned foreach loop

Hello here i am with freaky problem,i wants the first data and last data from for-each loop. for that i have seen this answer. this would be really helpful but here my condition is really a little bit complex.
I have loop as following
<?php
$count = 0;
$length = count($myDataArray);
foreach ($myDataArray as $value) {
if($count >= 7)
{
//Some Data to Print
//this is first data for me
<tr >
<td><?=$myfinaldate?></td>
<td><?=$stockdata[1]?></td>
<td><?=$stockdata[2]?></td>
<td><?=$stockdata[3]?></td>
<td <?php if($count == 8)echo "style='background-color:#47ff77;'"; ?>><?=$stockdata[4]?></td>
<td><?=$stockdata[5]?></td>
<td><?php echo $mydate; ?></td>
</tr>
<?php
}
$count++;
}
Now How can i Get First And Last Data from loop ?
I imagine you could use your length attribute.
As you have the total of your array, just check
myDataArray[0] and myDataArray[$length-1] ?
To fetch first and last value of the array use the below function :
$array = $myDataArray;
$array_values = array_values($myDataArray);
// get the first value in the array
print $array_values[0]; // prints 'first item'
// get the last value in the array
print $array_values[count($array_values) - 1]; // prints 'last item'
You can use array_values to remove the keys of an array and replace them with indices. If you do this, you can access the specified fields directly. Like this you can check for your requirements on the array without looping over it, as shown in the if-conditions below:
$length = count($myDataArray);
$dataArrayValues = array_values($myDataArray);
$wantedFields = [];
if ($length >= 8) {
$wantedFields[] = $dataArrayValues[7];
if ($length > 8) {
$wantedFields[] = end($dataArrayValues);
}
}
Due to the conditions you will not print the 8th field twice in case it is the last field as well.
foreach ($wantedFields as $value) {
<tr>
... //Your previous code
</tr>
}

add to cart using session ( delete ) php

How to delete specific item using session array. I've tried many time but my code still cant work. Can anyone help me to check my Code?
As the Remove Cart hyperlink pass the Product id that going to be delete.
but it cannot delete anyway. i have no idea where the error is .
cart.php
if (isset($_POST['lol']))
{
if (isset($_SESSION['cart']) === FALSE) { $_SESSION['cart']=array(); }
$proid=$_REQUEST["proid"];
array_push($_SESSION['cart'],$proid);
}
$total=0;
if (isset($_SESSION['cart']))
{
$total = 0;
foreach($_SESSION['cart'] as $proid )
{
$results = mysqli_query($con,"Select * from product where Product_ID = '$proid'");
$myrow = mysqli_fetch_array($results);
$price = $myrow['Product_Price'];
$total =$total + $price;
?>
<li class = "cartlist"><?php echo '<img src="data:image/jpeg;base64,' . base64_encode($myrow['Product_Pic']) . '" width="196" height="120">';?
><p><span style = "font-weight: bold; font-size: 1.2em;">
<?php echo $myrow["Product_Name"];?></span></br />
RM <?php echo $myrow["Product_Price"];?></br />
<?php echo $myrow["Product_Size"];?>MB <br/>
Remove From Cart</p> </li>
<?php
}
}
?>
<?php
if (isset($_GET['proid']))
$proid=$_REQUEST["proid"];
else
$proid = 1;
if (isset($_GET['action']))
$action =$_REQUEST['action'];
switch ($action)
{
case "remove" :
if (isset($_SESSION['cart']['$proid']))
{
$_SESSION['cart']['$proid']--;
unset($_SESSION['cart']['$proid']);
}
break;
case "empty" :
unset ($_SESSION['cart']);
break;
}
?>
The problem here is that you do not understand how arrays work in php.
Everything you store in an array is a key => value pair, even if you don't esplicitly set a key, php will set an integer value for you.
At some point you add a product id in your cart, like this:
array_push($_SESSION['cart'],$proid);
this can also be written like this:
$_SESSION['cart'][] = $proid;
(And if you look at array_push in the php documentation, it says it's best to write it this way)
This is an assignment, you are adding an element to the array, without specifying the key.
And here:
foreach($_SESSION['cart'] as $proid )
you are looping through the array values, ignoring the keys.
These lines of code suggest that the cart array will look like this:
array(
0 => 'id-for-product-one',
1 => 'id-for-product-two'
);
When you are trying to remove a product from the array, instead you are trying to look for the product as if that id you previously assigned as a value is now the key:
if (isset($_SESSION['cart']['$proid']))
This line has actually two mistakes.
The first is that by using single quotes the value of the string '$proid' is actually $proid. If you want to pass the value contained in $proid you can just omit the quotes, or in case you are building a more complex string you want the doublequotes (or use the . operator for string concatenation).
The second is that there is no array key for $prodid.
Given an array $a = array('key' => 'value') if you want to get 'value', you write $a['key'], what you are doing there is $a['value'].
The solutions here are two:
One is to assign the id both as a key and as a value.
The other is to use array_search to get the key of the element you want to remove and work from there.

How to Push and Pull Variable in SESSION type Array

I am willing to create a Shop Cart using simple PHP SESSION ARRAY. I tried to search different StackOverFlow problems, but none of those is giving me exact solution of my problem. Maybe I am doing any silly mistake. However,
I am doing this:
<!-- SHOPPING CART -->
<?php
if(isset($_REQUEST['atc']))
{
$item = $_REQUEST['atc'];
$_SESSION['cart'] = array();
array_push($_SESSION['cart'], $item);
//$_SESSION['cart'][] = $item;
foreach($_SESSION["cart"] as $key => $val)
{
echo $key . ">" . $val;
}
}
?>
<!-- SHOPPING CART -->
I am receiving $_REQUEST['ate'] (Integer Value/Product ID) when User is Clicking "ADD TO CART" Button on the same page. Then I am putting the value in $item, then I am declaring $_SESSION['cart'] as Array. Then I have tried array_push, and even tried $_SESSION['cart'][] to Push Integer Value. But each time only the first element is updated, therefore $_SESSION['cart'][0] is storing the value, not $_SESSION['cart'][1] or the rest.
The problem is that you redefine $_SESSION['cart'] every time as an empty array via $_SESSION['cart'] = array(); and then only push one element.
Try this
if(isset($_REQUEST['atc']))
{
$item = $_REQUEST['atc'];
if (!isSet($_SESSION['cart']))
$_SESSION['cart'] = array();
array_push($_SESSION['cart'], $item);
//$_SESSION['cart'][] = $item;
foreach($_SESSION["cart"] as $key => $val)
{
echo $key . ">" . $val;
}
}
Now only the first time a user wants to add an item, $_SESSION['cart'] will be initiated as an empty an array. The second time ($_SESSION['cart'] already is an array with one element), the second element will properly be pushed.
If you want the elements to be unique (as said in comments), you can use the elements id as key (and an array can only have unique keys).
if(isset($_REQUEST['atc']))
{
$item = $_REQUEST['atc'];
if (!isSet($_SESSION['cart']))
$_SESSION['cart'] = array();
if (!array_key_exists($item, $_SESSION['cart']))
$_SESSION['cart'][$item] = 1;
else
$_SESSION['cart'][$item]++;
foreach($_SESSION["cart"] as $key => $val)
{
echo $key . ">" . $val;
}
}
This will first check, if the item is already in the cart (array_key_exists), if not it will be added. If it is, it will increment the value, so you can keep track how often a specific item is in the cart (if you don't want that functionality, just lose the else statement)
The problem you are facing is that you override $_SESSION['cart'] every time you get an item. Try
if(!isset($_SESSION['cart'])
$_SESSION['cart'] = array();
//array_push($_SESSION['cart'], $item);
$_SESSION['cart'][] = $item;
Check first that the session is not already exist, then add items.
Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.

PHP - Count all elements of an Array that Satisfy a Condition [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Search for PHP array element containing string
I've created a mysql query that pulls through several products, all with the following information:
Product ID
Product Name
Product Price
and
Product Category
Further down the page, I've looped through these with a foreach and a few 'ifs' so it only displays those products where the name contains 'x' in one div and displays those products where the name contains 'y' in another div.
I'm struggling to count how many products are going to be in each div before I do the loop.
So essentially, what I'm asking is:
How do you count all elements in an array that satisfy a certain condition?
Added Code which shows the loop:
<div id="a">
<?php
$i = 1;
foreach ($products AS $product) {
if (strpos($product->name,'X') !== false) {
=$product->name
}
$i++;
} ?>
</div>
<div id="b">
$i = 1;
foreach ($products AS $product) {
if (strpos($product->name,'Y') !== false) {
=$product->name
}
$i++;
} ?>
</div>
I'd like to know how many of these are going to be in here before I actually do the loop.
Well, without seeing the code, so generally speaking, if you're going to split them anyway, you might as well do that up-front?
<?php
// getting all the results.
$products = $db->query('SELECT name FROM foo')->fetchAll();
$div1 = array_filter($products, function($product) {
// condition which makes a result belong to div1.
return substr('X', $product->name) !== false;
});
$div2 = array_filter($products, function($product) {
// condition which makes a result belong to div2.
return substr('Y', $product->name) !== false;
});
printf("%d elements in div1", count($div1));
printf("%d elements in div2", count($div2));
// then print the divs. No need for ifs here, because results are already filtered.
echo '<div id="a">' . PHP_EOL;
foreach( $div1 as $product ) {
echo $product->name;
}
echo '</div>';
echo '<div id="b">' . PHP_EOL;
foreach( $div2 as $product ) {
echo $product->name;
}
echo '</div>';
That being said: you should take notice of the comment which says "This is normally faster in SQL", because it is the more sane approach if you want to filter the values.
EDIT: Changed the name of the variables to adapt the variable names in the example code.
Use an array-filter: http://www.php.net/manual/en/function.array-filter.php
array array_filter ( array $input [, callable $callback = "" ] )
Iterates over each value in the input array passing them to the callback function. If the callback function returns true, the current value from input is returned into the result array. Array keys are preserved.
<?php
function odd($var)
{
// returns whether the input integer is odd
return($var & 1);
}
function even($var)
{
// returns whether the input integer is even
return(!($var & 1));
}
$array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
$array2 = array(6, 7, 8, 9, 10, 11, 12);
echo "Odd :\n";
print_r(array_filter($array1, "odd"));
echo "Even:\n";
print_r(array_filter($array2, "even"));
?>
But be aware, this is a loop though, and your the SQL query will be faster.

Categories