... It's not as silly as it sounds...
I have the following code, which is used by my ajax table script to display database stuff on the page in a table.
foreach($ct->data as $key => $value){
$ct->data[$key][2]=''.$ct->data[$key][2].'';
$ct->data[$key][3]=''.$ct->data[$key][3].'';
if($ct->data[$key][4] == "" || $ct->data[$key][4] == null)
$ct->data[$key][4]='Edit Charge.';
else
$ct->data[$key][4]=''.$ct->data[$key][4].'';
$Total =$Total+ $ct->data[$key][3];
$freight =$freight+ $ct->data[$key][4];
}
And as you can see, in the foreach loop, I am trying to add up the contents of 2 columns.
The $Total column or, $ct->data[$key][3] lists the Prices for each row of products, and the $freight column does the same for each row of Freight charges.
And inside the foreach loop, I am trying to add together the total amount of prices, and Freight charges.
I'm not sure if I'm doing it the right way, because when I check the database, it just adds '0' (without the quotes). So it's not adding up!
For example, if there are a total of 3 rows in the table, and each product is 1 (dollar), it should add up to 3, right? And same goes for the $freight ones.
Can someone please tell me what I'm doing wrong here?
You are setting data[$key][3] equal to some HTML hyper link. Its not something that can be "totalled"
Is line 3 not setting the value you're adding to $Total to a string?
$ct->data[$key][3]=''.$ct->data[$key][3].'';
and then
$Total =$Total+ $ct->data[$key][3];
If you remove the first one, the second might work better.
Related
I have the following SQL statement:
$query = "SELECT item, COUNT(*) as number FROM shop GROUP BY item";
This will give me the following result:
item number
item1 23
item2 15
item3 4
I want to use this to make menu items, so normally the menu would look:
item1
item2
item3
But I want to do a check if an item has less than 10 records, that I don't want to display this item.
So in this example, the menu would be like:
item1
item2
Any idea how to achieve this?
I would like to do this in PHP because I need all the items in the query but will only want to show them which are greater then 10 and need the other items later on.
If you want to do this in PHP then you can do like this
function filterArray($value){
return ($value.number > 10);
}
$filteredArray = array_filter($yourDBArray, 'filterArray');
foreach($filteredArray as $k => $v){
//your desired array
}
In terms of speed Mysql option is good as suggested above.
Just change your query from
SELECT item, COUNT(*) as number FROM shop GROUP BY item
to
SELECT item, COUNT(*) as number FROM shop GROUP BY item HAVING number>=10
As you really need to perform this in PHP you could use array_filter() which, using a closure, will remove items which number is less than 10:
$more_than_ten = array_filter($items, function ($i) { return $i['number'] >= 10; });
Doing it with SQL would be a better solution (about performances). In case you'd need it, you could use the HAVING clause (you can't perform a WHERE number >= 10):
SELECT
item,
COUNT(*) as number
FROM shop
GROUP BY item
HAVING number >= 10
I noticed php is tagged. For the sake of options, here's how I'd go about separating the unneeded data in php if you were to get it from the database as-is:
foreach ($data as $item) {
$num = (int) $item['number']; // force of habit
if ($num >= 10) {
// display it
}
}
I'd probably separate the data at the database step, but this works if it's the route you want to take.
There is two options to filter the data so only the rows with more then 10 will appear.
At the SQL query
__
SELECT item, COUNT(*) as number FROM shop GROUP BY item HAVING number > 9
This will cause you to recieve only the requested rows from the database
Filter with PHP - every time you want to print the menu or testing it out, just can the value of 'number' in the array reutrned from the query. You can also allocate new array and insert all the values that contains 'number' that bigger then 10.
I am working on some scripts to automate some things inside our webshop.
I have looked through many forums and questions.
Now I almost have finished my script but there is a small thing that doesn't work but I can not think of what I am doing wrong.
What the goal of this script is, is to get products that has the same attribute value as the values in an array (pulled from DB).
So here is my code:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once('../app/Mage.php');
require_once('db.php');
Mage::app();
$db = db_connection();
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect('ean');
$getean = $db->prepare('SELECT ean_l FROM mytable');
$getean->execute();
$allean = $getean->fetchAll();
foreach($allean as $ean) {
$collection->addFieldToFilter(array(
array('attribute'=>'ean','eq'=>'' . $ean['ean_l'] . ''),
));
echo 'ean_l: ' . $ean['ean_l'] . '<br>';
foreach ($collection as $product) {
echo $product['entity_id'];
}
}
So here's how it works:
We select an attribute (ean).
We get a list of all ean numbers from the database.
We loop through the list and compare any product with the ean number.
Then we loop through the collection and get the id of the corresponding product.
Yet, all $product['entity_id']'s are 273. It is correct that the entity_id is 273, but there is also product 274 with a corresponding ean number.
Here is the result from the script (it's alot more):
So why is this? Because in my reasoning, it changes the ean_l every loop and it equalizes it with the attribute values.
And then it should change the collection, right?
So shouldn't it at least show 274 at some point?
This question is not especially for Magento programmers, but other programmers can help too, so I figured to post it on SO.
Magento comes with powerfull filtering and queries into collections. If that doesn't satisfy, you can always extend with custom queries into getSelect function. Some info here.
Using addFieldToFilter into that foreach will filter the remaining values after another iterated filtering. So it's not good.
$allean = array("of", "ean", "values", "needed", "for", "filtering");
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect('ean');
//addAttributeToFilter for EAV collections
$collection->addAttributeToFilter('ean', array('in' => $allean)); //not addFieldToFilter
$collection->getColumnValues('entity_id');
var_dump($collection); //will output an array of product_ids
Alternative, if you want to group by ean values you should remove getColumnValues and run group command.
You can find additional info here.
Or you can just remove getColumnValues, start a foreach($collection as $product) and group manually or do what you want with those filtered products.
I have a SESSION['cart'] with ID numbers only. I have a form passing the ID with a remove button. Once passed to my controller, I cannot figure out how to write the code that uses the ID ($_POST['id']) to delete the item from the SESSION['cart'].
I can loop through and display the array contents, but I cannot figure out how to delete based on ID passed from the form.
How do I loop through the SESSION['cart'] array to find a match with the ID passed from my delete form, and then delete that ID? I know that unset($_SESSION['cart'][X] deletes the ID at index X, but I cannot figure out how to loop through all the elements to find a match.
I have read a number of related issues in this forum but have been unable to apply any of those solutions to resolve this challenge. Any assistance is appreciated.
The way you have your values ($products = array(3,7,99,152)) isn't a very good method. Every time you want to perform an action, you have to loop through the array, you don't want that. Apart from that, how do you store quantity? Or variations like e.g. size or color?
if your structure is $array[ ID_OF_PRODUCT ], you can simply do this:
unset( $_SESSION['cart'][$_POST['id']] ); // Instant access via the key!
This should be the method to use. This allows you to create an array like this, with advanced info, but with easy access (42/63 are example id's)
$_SESSION['cart']['products'][42] = array(
'quantity' = 11,
'size' = 'large',
'color' = 'blue'
);
$_SESSION['cart']['products'][63] = array(
'quantity' = 9,
'size' = 'small',
'color' = 'red'
);
This way you can access a lot of info with the product ID, and now also see which size and color (both just examples) the user selected. You may not have need for this now, but you will further down the road :)
As you might see, you can easily do stuff with the item:
isset($_SESSION['cart'][$_POST['id']]); // check if the product exists
unset($_SESSION['cart'][$_POST['id']]); // remove the product
echo $_SESSION['cart'][$_POST['id']]['quantity']; // get the quantity.
Not a loop in the code. You should only use loops when you have to, try to somewhat avoid them because often their slow. Say you have an extreme case of 1000 items in your shop, and you need to delete no999... That'll take a noticable moment.
Here is the code to do it right:
$id = $_POST['id'];
$items = $_SESSION["cart"];
if(($key = array_search($id, $items)) !== false) {
unset($items[$key]);
}
$_SESSION["cart"] = array_values($items);
Advice
Beside item ID, you can also sve item count in SESSION array because user can add several times same item into cart. In that case your $_SESSION["card"] should be structured like:
array(
'1'=>12,//Item with ID=1 is added 12 times in shopping cart
'17'=>2,//Item with ID=17 is added 2 times in shopping cart etc.
'32'=>12,
)
Bit stuck on how to achieve this.....
I have a PHP page which shows information for one record in a table. These records include a unique key (image_id) AND a name (image_name).
In order to display the correct record, I am using a search function on a previous page which results in a URL parameter (imageinfo.php?image_id=1 etc).
My problem is that I wish to add forward and back arrows to the table to cycle through different records, BUT based on the alphabetical order of 'image_name' rather than the numerical order of 'image_id.
I'm really not sure how to achieve this, so any help would be appreciated.
Something like this: (I hope the comments will explain)
<?php
$data = array(
123 => "B",
321 => "C",
124 => "A"
);
$id = 123; // This is the current image id
asort($data); // Sort the array based on values (names)
// Advance the internal pointer until it points to the current image
while(current($data) != $data[$id])
next($data);
// TODO: Also check whether next is past end here
echo next($data); // Should be C
In our order proces it is possible to send an invoice for a partial order. So when a couple of order lines are being shipped, an invoice have to be send also.
To make this possible I use this code:
$invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice($items);
if (!$invoice->getTotalQty()) {
Mage::throwException(Mage::helper('core')->__('Cannot create an invoice without products.'));
}
$invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
$invoice->register();
$transactionSave = Mage::getModel('core/resource_transaction')
->addObject($invoice)
->addObject($invoice->getOrder());
$transactionSave->save();
$invoice->sendEmail();
$invoice->setEmailSent(true);
$invoice->save();
Where the $items variable is an array containing the order ids and the amount of products to be invoiced.
The created invoice shows the correct products to be invoiced, but somehow the totals aren't updated. The totals still are the totals of the complete order, instead of the partial invoice.
I probably have to update or recalculate the totals but can't find the right code to force the update.
Anyone around who can put me in the right direction?
Well, it seems I have found the problem. The functionality as described above works manually executing it in the administrator interface. The code as enclosed above I only got to work by changing a core file of Magento.
If you change line 103 of Mage_Sales_Model_Service_Order from continue; to $qty = 0; the functionality works.
In short, this is what happens. With continue the second row item isn't added to the invoice which the invoice makes thinks the curren item is the last item of the whole order and therefore needs to invoice the complete outstanding amount. In my case the invoice I did want to invoice and the row I didn't want to invoice.
I've submitted it as issue on the Magento issue list.
Today I faced with exactly this problem, but I found a more elegant way to solve it without editing the core. The solution is to pass the products that we don't want to invoice, with 0 quantity.
In this way, the code you changed in core will act exactly like in your solution :)
As an example if I have 2 products in my order:
array(
1234 => 1,
1235 => 2
)
passing this array:
$qtys = array(
1234 => 1,
1235 => 0
)
will force this code:
// Mage_Sales_Model_Service_Order: lines 97-103
if (isset($qtys[$orderItem->getId()])) { // here's the magic
$qty = (float) $qtys[$orderItem->getId()];
} elseif (!count($qtys)) {
$qty = $orderItem->getQtyToInvoice();
} else {
continue; // the line to edit according to previous solution
}
to act exactly like in your solution, so you don't have to edit core code.
Hope it helps :)
OK - took me a bit, but now I see how to correctly create the array.
foreach ($items as $itemId => $item) {
$itemQtyToShip = $item->getQtyToShip()*1;
if ($itemQtyToShip>0) {
$itemQtyOnHand = $stockItem->getQty()*1;
if ($itemQtyOnHand>0) {
//use the order item id as key
//set the amount to invoice for as the value
$toShip[$item->getId()] = $itemQtyToShip;
} else {
//if not shipping the item set the qty to 0
$toShip[$item->getId()] = 0;
}
}
$invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice($toShip);
This creates a proper invoice.