How to compare values in a loop? - php

I have orders come in. Each order has a type i.e 'Vanilla' and a size i.e 'Mini with a quantity.
If there are 5 Mini Vanillas I want it to display once not 5 times. I also want to tally the quantity.
Here is one of the many things I attempted
$prevSize = null;
$prevType= null;
foreach ($orders as $order){
echo '<tr>';
$new_order = new WC_Order();
$order_items = $new_order->get_items();
foreach ($order_items as $order_item ){
$currentSize = $order_item['pa_size'];
$currentType = wp_get_post_terms( $order_item['product_id'],'pa_ct');
$currentType = $currentType[0]->name;
if($prevSize != $currentSize){
echo $currentType . '<br>';
echo $currentSize . '<br>';
}
$count += $order_item['qty'];
echo $count;
}
$prevSize = $currentSize;
$prevType = $currentType;}

We have analyzed your query, and according to your need, here is my solution:
$order_type = array();
foreach ($orders as $order){
echo '<tr>';
$new_order = new WC_Order();
$order_items = $new_order->get_items();
$count = 0;
foreach ($order_items as $order_item ){
$currentSize = $order_item['pa_size'];
$currentType = wp_get_post_terms( $order_item['product_id'],'pa_ct');
$currentType = $currentType[0]->name;
$temp_order_type = $currentSize.'_'.$currentType;
if(!in_array($temp_order_type, $order_type)){
$order_type[] = $temp_order_type;
echo $currentType . '<br>';
echo $currentSize . '<br>';
}
$count += $order_item['qty'];
}
echo $count;
}
Above code will display each order type once not display multiple times. And display the quantity ordered in each order.

Related

For each loop not looping all rows

I'm trying to loop all rows of a table name cart but the foreach is only displaying the last row entered and always ignore the previous ones. Say I have 5 products in the cart_table well only product_id[5] will be displayed. If user adds a sixth item, only product_id[6] will now be displayed. The $item_count will also always equal 1 as if there is only one item when there are multiple. To my understanding in the foreach($items as $item) $items is not seen as an array even with multiple items. when I var_dump($items); it shows array(1) { [0]=>...
add_cart.php
<?php
ob_start();
require_once $_SERVER['DOCUMENT_ROOT'].'/ecommerce/core/init.php';
$product_id = isset($_POST['product_id'])? sanitize($_POST['product_id']):'';
$size = isset($_POST['size'])? sanitize($_POST['size']):'';
$available = isset($_POST['available'])? sanitize($_POST['available']):'';
$quantity = isset($_POST['quantity'])? sanitize($_POST['quantity']):'';
$item = array();
$item[] = array(
'id' => $product_id,
'size' => $size,
'quantity' => $quantity,
'available' => $available
);
$domain =($_SERVER['HTTP_HOST'] != 'localhost')?'.'.$_SERVER['HTTP_HOST']:false;
$query = $db->query("SELECT * FROM product WHERE id = '{$product_id}'");
$product = mysqli_fetch_assoc($query);
$_SESSION['success_flash'] = $product['prod_name']. ' was added to your cart.';
//check if the cart cookie exists
if (is_array($cart_id != ' ')) {
$cartQ = $db->query("SELECT * FROM cart WHERE id = '{$cart_id}'");
$cart = mysqli_fetch_assoc($cartQ);
$previous_items = json_decode($cart['items'],true);
$item_match = 0;
$new_items = array();
foreach($previous_items as $pitem){
if ($item[0]['id'] == $pitem['id'] && $item[0]['size'] == $pitem['size']) {
$pitem['quantity'] = $pitem['quantity'] + $item[0]['quantity'];
if ($pitem['quantity'] > $available) {
$pitem['quantity'] = $available;
}
$item_match = 1;
}
$new_items[] = $pitem;
}
if ($item_match != 1) {
$new_items = array_merge($item,$previous_items);
}
$items_json = json_encode($new_items);
$cart_expire = date("Y-m-d H:i:s",strtotime("+30 days"));
$db->query("UPDATE cart SET items = '{$items_json}', expire_date = '{$cart_expire}' WHERE id = '{cart_id}'");
setcookie(CART_COOKIE,'',1,"/",$domain,false);
setcookie(CART_COOKIE,$cart_id,CART_COOKIE_EXPIRE,'/',$domain,false);
}else{
// add to databse and set cookie
$items_json = json_encode($item);
$cart_expire = date("Y-m-d H:i:s",strtotime("+30 days"));
$db->query("INSERT INTO cart (items,expire_date) VALUES ('{$items_json}','{$cart_expire}')");
$cart_id = $db->insert_id;
setcookie(CART_COOKIE,$cart_id,CART_COOKIE_EXPIRE,'/',$domain,false);
}
?>
cart.php
<?php
require_once 'core/init.php';
//include 'includes/headerpartial.php';
if($cart_id != ' ') {
$cartQ = $db->query("SELECT * FROM cart WHERE id ='{$cart_id}' ");
$result = mysqli_fetch_assoc($cartQ);
$items = json_decode($result['items'], true);
$i = 1;
$sub_total = 0;
$item_count = 0;
}
?>
<?php if($cart_id == ' '): ?>
<div class="bg-danger">
<p class='text-center text-danger'>Your cart is empty.</p>
</div>
<?php else: ?>
<?php
foreach ($items as $item) {
var_export($items);
$product_id = $item['id'];
$productQuery = $db->query("SELECT * FROM product WHERE id ='{$product_id}' ");
$product = mysqli_fetch_assoc($productQuery);
$sArray = explode(',', $product['sizes']);
/* foreach ($sArray as $sizeString) {
$s = explode(':', $sizeString);
if($s[0] == $item['size']) {
$available = $s[1];
}
}*/
?>
<tr class="p">
<td class="image"><img src="<?= $product['image_1']; ?>"/></td>
<td class="name"><?= $product['prod_name']; ?></td>
<td class="price"><?= money($product['price']); ?></td>
<td class="quantity"><?= $item['quantity']; ?></td>
<td class="pricesubtotal"><?= money($item['quantity'] * $product['price']); ?></td>
<td class="remove">
<div>&times</div>
</td>
</tr>
<?php
$i ++;
$item_count += $item['quantity'];
$sub_total += ($product['price'] * $item['quantity']);
}
$tax = TAXRATE * $sub_total;
$tax = number_format($tax, 2);
$grand_total = $tax + $sub_total;
<?php endif;?>
Here is one of the problems. You told me that your id is an auto increment int, so I would like to propose this answer. The problem is in your sql command.
UPDATE cart SET items = '{$items_json}', expire_date = '{$cart_expire}' WHERE id = {cart_id}
Be sure to put that command in quotes. Also, I highly recommend preparing the JSON with this command:
$itemJson = addslashes($itemJson);
then, you can run the command. Another possibility would be to use the prepare method from mysqli. Here is a link to some examples:
w3schools.com
if you have any further questions, feel free to update your question, but be sure to #McStuffins in the comments.

what are the different ways for this code to work

The following is part of a personal budgeting program I'm writing.
This code pulls line item information from multiple tables and writes it into an array and then displays the information by transid => family => category => lineItems. Everything works, and I get the results I want out of it. My question is if there is a more efficient way to accomplish this task?
Since this is a personal program, I'm only asking so that I can improve my coding abilities.
<?php
include ('../cfg/connect.php');
$s = " : ";
$br = "<br>";
$ul = "<ul>";
$li = "<li>";
$_ul = "</ul>";
$_li = "</li>";
$data = [];
$itemCount = 0;
$arrayItemCount = 0;
$categoryQry = "SELECT a.itemQty, b.transDate, b.transID, b.amount, a.itemPrice, a.itemCategory, c.catFamily, a.itemName, a.itemSource FROM budget.lineItems AS a JOIN budget.quickEntry AS b ON a.transID = b.transID JOIN budget.categories AS c ON a.itemCategory = c.catName WHERE b.processed = 'y' ORDER BY c.catFamily, c.catName, b.transDate";
$categories = $conn->prepare ($categoryQry);
$categories->execute ();
$categories->store_result ();
$categories->bind_result ($itemQty, $transDate, $transID, $totalPrice, $itemPrice, $category, $family, $itemName, $source);
while ($categories->fetch ()) {
if (!isset($data[$transID]['amount'])) {
$data[$transID]['amount'] = 0;
}
if (!isset($data[$transID]['line'])) {
$data[$transID]['line'] = '';
}
if (!isset($data[$transID]['line'][$family]['amount'])) {
$data[$transID]['line'][$family]['amount'] = 0;
}
if (!isset($data[$transID]['line'][$family]['line'])) {
$data[$transID]['line'][$family]['line'] = '';
}
if (!isset($data[$transID]['line'][$family]['line'][$category]['amount'])) {
$data[$transID]['line'][$family]['line'][$category]['amount'] = 0;
}
if (!isset($data[$transID]['line'][$family]['line'][$category]['line'])) {
$data[$transID]['line'][$family]['line'][$category]['line'] = '';
}
$itemCount++;
$qtyPrice = $itemPrice * $itemQty;
$data[$transID]['amount'] += $qtyPrice;
$data[$transID]['transDate'] = $transDate;
$data[$transID]['source'] = $source;
$data[$transID]['line'][$family]['amount'] += $qtyPrice;
$data[$transID]['line'][$family]['line'][$category]['amount'] += $qtyPrice;
$data[$transID]['line'][$family]['line'][$category]['line'][$itemName] = ['itemQty' => $itemQty, 'itemPrice' => $itemPrice];
}
foreach ($data as $transID => $transValue) {
echo $transID .$s.$transValue['transDate'].$s.$transValue['source'].$s.$transValue['amount']. $ul;
foreach ($transValue['line'] as $category => $categoryValue) {
echo $li . $category .$s.$categoryValue['amount']. $ul;
foreach ($categoryValue['line'] as $line => $lineValue) {
echo $li . $line .$s.$lineValue['amount']. $ul;
foreach ($lineValue['line'] as $item => $details) {
echo $li . $item .$s . $details['itemQty'] . $s . $details['itemPrice'] . $_li;
}
echo $_ul . $_li;
}
echo $_ul . $_li;
}
echo $_ul . $br;
}

Mysql row returns last value in array, but I expect the whole row

Here is my cart code:
function cart() {
$total = 0;
$item_quantity = 0;
$item_name = 0;
$item_number = 1;
$amount = 1;
$quantity = 1;
foreach ($_SESSION as $name => $value) {
if($value > 0 ) {
if(substr($name, 0, 8) == "product_"){
$length = strlen($name - 8);
$id = substr($name, 8 , $length);
$query = query("SELECT * FROM products WHERE product_id = " . escape_string($id)." ");
confirm($query);
$titleArr = array();
while($row = fetch_array($query)) {
$titleArr[$id] = $row['product_title'];
$product_name = implode(",", $titleArr);
$order_product = $product_name . "-". $value;
$sub = $row['product_price']*$value;
$item_quantity +=$value;
$item_number++;
$amount++;
$quantity++;
$id++;
}
$_SESSION['item_total'] = $total += $sub;
$_SESSION['item_quantity'] = $item_quantity;
$_SESSION['item_name'] = $order_product;
}
}
}
}
I searched online for a long time, please advise.
$_SESSION['item_name'] = $order_product;
It gives last value from fetch_array I want all product title on cart page.
Either of these changes should work...
This puts the m all into an array...
$_SESSION['item_name'] = array();
foreach ($_SESSION as $name => $value) {
...
$_SESSION['item_total'] = $total += $sub;
$_SESSION['item_quantity'] = $item_quantity;
array_push($_SESSION['item_name'],$order_product);
...
}
This puts them into a comma separated string...
$_SESSION['item_name'] = '';
foreach ($_SESSION as $name => $value) {
...
$_SESSION['item_total'] = $total += $sub;
$_SESSION['item_quantity'] = $item_quantity;
$_SESSION['item_name'] .= $order_product.', ';
...
}
$_SESSION['item_name'] = rtrim($_SESSION['item_name'],' ');
$_SESSION['item_name'] = rtrim($_SESSION['item_name'],',');
Please make two dimensional Array, if you want to show all product title on cart page.
Replace this
$order_product = $product_name . "-". $value;
with
$order_product[] = $product_name . "-". $value;
Before while loop assign the array:-
$order_product = array();
updated while loop
$total = 0
while($row = fetch_array($query)) {
$titleArr[$id] = $row['product_title'];
$product_name = implode(",", $titleArr);
$order_product = $product_name . "-". $value;
$sub = $row['product_price']*$value;
$item_quantity +=$value;
$item_number++;
$amount++;
$quantity++;
$id++;
$total += $sub;
$_SESSION['item_name'][] = $order_product;
}
$_SESSION['item_total'] = $total;
$_SESSION['item_quantity'] = $item_quantity;

Limiting the number of feed items displayed

Below is roughly what I am using to display items from a feed. It works fine but the feed has many items and I want to be able to just display the first 5 items in the feed. How can this e done?
<?php
$theurl = 'http://www.theurl.com/feed.xml';
$xml = simplexml_load_file($theurl);
$result = $xml->xpath("/items/item");
foreach ($result as $item) {
$date = $item->date;
$title = $item->title;
echo 'The title is '. $title.' and the date is '. $date .'';
} ?>
foreach ($result as $i => $item) {
if ($i == 5) {
break;
}
echo 'The title is '.$item->title.' and the date is '. $item->date;
}
A for loop may be more suitable for this than a foreach loop:
for ($i=0; $i<=4; $i++) {
echo 'The title is '.$result[$i]->title.' and the date is '. $result[$i]->date;
}
This loop has a much higher performance when not modifying anything in the array, so if speed matters I'd recommend it.
Just do it as part of the XPath query:
<?php
$theurl = 'http://www.theurl.com/feed.xml';
$xml = simplexml_load_file($theurl);
$result = $xml->xpath('/items/item[position() <= 5]');
foreach ($result as $item) {
$date = $item->date;
$title = $item->title;
echo 'The title is '. $title.' and the date is '. $date . '';
}
?>
Here's a demo!

About Limiting Rss Feed

I want only the latest 5 feeds to be shown on my website.
I am using the following code to fetch rss feed... Can any one help to limited feeds to be shown... Thank You In ADVANCE :)
CODE THAT AM USING
<?php
require_once('rss_fetch.inc');
$url = 'http://news.google.com/news?ned=us&topic=h&output=rss';
$rss = fetch_rss($url);
echo "Site: ", $rss->channel['title'], "<br>\n";
foreach ($rss->items as $item ) {
$title = $item['title'];
$url = $item['link'];
$desc = $item['description'];
$category = $item['category'];
echo "<a href=$url>$title</a>$desc <br/>CATEGORY : $category <br/><br/> ";
}
?>
Limit it using foreach?
foreach ($rss->items as $i => $item ) { // use $i as counter
$title = $item['title'];
$url = $item['link'];
$desc = $item['description'];
$category = $item['category'];
echo "<a href=$url>$title</a>$desc <br/>CATEGORY : $category <br/><br/> ";
if($i == 4) break; // add this, == 4 is because $i starts from 0
}
If you're looking to limit the number of posts, you just need to keep track of them and break out of the foreach loop when applicable, e.g.
<?php
require_once('rss_fetch.inc');
$url = 'http://news.google.com/news?ned=us&topic=h&output=rss';
$rss = fetch_rss($url);
echo "Site: ", $rss->channel['title'], "<br>\n";
$numposts = 0;
$maxposts = 5;
foreach ($rss->items as $item ) {
$numposts++;
if ($numposts<=$maxposts) {
$title = $item['title'];
$url = $item['link'];
$desc = $item['description'];
$category = $item['category'];
echo "<a href=$url>$title</a>$desc <br/>CATEGORY : $category <br/><br/> ";
} else {
break;
}
}
?>

Categories