Sum of Foreach Loop - php

I'm trying to total a bill balance with a program I'm working on in PHP.
The code I use to pull the pricing is as such.
public function PackagePricing($arg) {
$query = <<<SQL
SELECT packageID
FROM customer_packages
WHERE active = :true
AND customerID = :arg
SQL;
$resource = $this->db->db->prepare( $query );
$resource->execute( array (
":true" => 1,
":arg" => 1,
));
foreach($resource as $row) {
self::GetPricing($row['packageID']);
}
}
public function GetPricing($arg) {
$query = <<<SQL
SELECT price
FROM products
WHERE id = :arg
SQL;
$resource = $this->db->db->prepare( $query );
$resource->execute( array (
":arg" => $arg,
));
$totalBill = 0;
foreach($resource as $row) {
$totalBill+= $row['price'];
}
echo $totalBill;
}
Now by my understanding this should work, but what I'm getting in turn is:
On the right you can see the billing total and rather than totaling out it's giving me each individually.

The error seems quite obvious. Here's your sequence in different words :
Get all packages ID.
Foreach package ID, get the price of the item (only one result is returned)
For that single result, add up all the prices (you only get one). Print it and go back to 2.
What you see is not 2 prices that have been added as strings in some sort of way. You simply prints subsequently 2 different prices. 10 & 30
GetPricing should return a price, and the foreach loop that calls it should make the sum.
$total = 0;
foreach($resource as $row)
{
$total += self::GetPricing($row['packageID']);
}
Hope this helps.

Related

Total Invoices - Receipts not adding up

I have the next issue - I have a table invoices and a table with receipts. An invoice is created by an agent and I want to get the sold for each agent but the numbers are wrong.
Here is what I've tried:
$agents = Agent::get();
$invoices_receipts_agent = array();
foreach ($agents as $agent) {
$payment_invoice = 0;
$payment_recepit = 0;
$id_agent = $agent->id_agent;
$invoices = Invoice::whereAgent_id($id_agent)->get();
foreach ($invoices as $invoice) {
$payment_invoice = $payment_invoice + $invoice->total_pay;
$recepits = Recepit::whereInvoice_id($invoice->id_invoice)->get();
if (count($recepits) > 0) {
foreach ($recepits as $recepit) {
$payment_recepit = $payment_recepit + $recepit->amount_payd;
}
}
}
$total = $payment_invoice - $payment_recepit;
$total_agents = ['name' => $agent->name, 'total' => $total];
array_push($invoices_receipts_agent, $total_agents);
}
I made a test and created two invoices for the agent with ID 5
First invoice: 10
Second invoice : 20
Total invoices: 30
Then I did a recepit for the second invoice and found the expected total:
Total: 10 + 20 - 20 = 10 (correct total)
And that's great, but I have an agent with 3600 invoices and something is wrong the total. The total (total = invoices - recepits) is too big, but I can't figure out why.
Extra detail: the fields for the numbers are float.
First of all, you have an easier way to handle this issue using Eloquent Relationships.
In this case, can define One-to-Many relationship between Agent and Invoice as:
class Agent {
...
function invoices(){
return $this->hasMany('App-Namespace\Invoice')
}
}
...and define the inverse relationship on Invoice.
Then, you must do same between Invoice and Receipt models, since an Invoice can have one to many receipts.
So, if Agents table primary key is id you could say:
$agent = Agent::find($agent_id)->invoices->get();
...to get an agent invoices; or:
$invoice = Invoice::find($invoice_id)->receipts->get();
...to get all receipts for a specific invoice.
And finally implement your code:
$agents = Agent::all();
$invoices_receipts_agent = array();
foreach ($agents as $agent) {
$payment_invoice = 0;
$invoices = $agent->invoices->get();
foreach ($invoices as $invoice){
$payment_invoice += $invoice->total_pay;
$payment_receipt += $invoice->receipts->sum('amount_paid');
}
$total = $payment_invoice + $payment_receipt;
$invoices_receipts_agent[] = ['name' => $agent->name, 'total' => $total];
}
Note: I have used sum collection function to get sum of values of column amount_paid of a particular receipt. You could do same to get sum of total_pay column of an invoice like:
$total_paid = $agent->invoices()->sum('total_pay');
Can you confirm it this current version of your code?
I see some typos like in:
$recepits = Recepit::whereInvoice_id($invoice->id_invoice)->get();
if (count($receipts) > 0) {
Here we have issues:
Variable is named $recepits, but then called in next line with other name ($receipts).
$receipts should be a collection (result of Eloquent query) not an array. So to get count you have to say: $receipts->count()
If this is your final code, those are definitly error which are affecting your result.

Associative array's loaded from database and display as 'columns'

I am trying to create an overview of product properties, for an invoice system.
So far, most things are comming together using classes and PDO.
I have the following issue.
In my class, i've created a function that builds my products array.
It loads some information from the database, to build this array.
This array, i want to use to display all the products i have selected:
$prod1 - $prod1Name - $prod1Descr - $prod1Price
$prod2 - $prod2name - $prod2Descr - $prod2Price
etc.
I figured that the Associative array would help me creating columns.
Though the problem is, that i do not understand a bit how to create multiple lines and columns this way.
I was thinking of something like:
$prod[1]["name"] - $prod[1]["descr"] - etc
Then to use this in a foreach loop to create as many new lines as required.
The only thing i could come up with is on my index.php (as shown below), cause using an index (the [1] defenition) does not seem to work the way i think it should be implemented.
For my understanding, i assigend the var in my class as an array, then redefine an array when loading the database information.
Could anyone tell me how i could try to solve this issue?
I have the following class:
<?
class Invoice{
var $vendorID;
var $product = array();
function product_array(){
global $db;
$query = $db->conn->prepare('
SELECT ProductName, ProductDescription, ProductDuration, ProductPriceInclVat, ProductPriceExclVat, ProductVatType
FROM products WHERE VendorID = :VendorID
');
$array = array (
'VendorID' => $this->vendorID
);
$query->execute($array);
$result = $query->fetchall();
if (empty($result)){
echo"Could not find any products matching your criteria.";
die;
} else {
foreach($result as $row) {
$this->product = array("Name" => $row['ProductName'],
"Description" => $row['ProductDescription'],
"Duration" => $row['ProductDuration'],
"PriceExclVat" => $row['ProductPriceExclVat'],
"PriceInclVat" => $row['ProductPriceInclVat'],
"VatType" => $row['ProductVatType']
);
}
}
}
}
?>
and then i have the following code on my index.php:
<?
$invoice = new Invoice();
foreach ($invoice->product as $key => $value){
echo $key . "<br>";
echo $value . "$value";
echo "<br>";
}
?>
When you are assigning the result arrays to the product property you are overwriting the array every time. You need to append to the array instead, so something like:
$this->product = array();
foreach($result as $row) {
$this->product[] = array(...);
}
Alternatively, you could just assign the results of fetchAll to the product property if you don't need to rename the field keys (or you could alias them in the SQL).
$query = $db->conn->prepare('
SELECT ProductName as Name,
ProductDescription as Description,
ProductDuration as Duration,
ProductPriceInclVat as PriceInclVat,
ProductPriceExclVat as PriceExclVat,
ProductVatType as VatType
FROM products WHERE VendorID = :VendorID
');
$array = array (
'VendorID' => $this->vendorID
);
$query->execute($array);
$product = $query->fetchall(PDO::FETCH_ASSOC);
The $product is now in the format you require.
After this you can avoid foreach loop in class invoice.
Other thing i noticed that you have made function product_array() which is not called,
so in index.php you are getting empty array (defined in class Invoice).
So in Invoice class it should be
$product = product_array()
and product_array function should return the value.

PHP MySQL building a 3 Tier multi dimensional array

So I have my query, its returning results as expect all is swell, except today my designer through in a wrench. Which seems to be throwing me off my game a bit, maybe its cause Im to tired who knows, anyway..
I am to create a 3 tier array
primary category, sub category (which can have multiples per primary), and the item list per sub category which could be 1 to 100 items.
I've tried foreach, while, for loops. All typically starting with $final = array(); then the loop below that.
trying to build arrays like:
$final[$row['primary]][$row['sub']][] = $row['item]
$final[$row['primary]][$row['sub']] = $row['item]
I've tried defining them each as there own array to use array_push() on. And various other tactics and I am failing horribly. I need a fresh minded person to help me out here. From what type of loop would best suit my need to how I can construct my array(s) to build out according to plan.
The Desired outcome would be
array(
primary = array
(
sub = array
(
itemA,
itemB,
itemC
),
sub = array
(
itemA,
itemB,
itemC
),
),
primary = array
(
sub = array
(
itemA,
itemB,
itemC
),
sub = array
(
itemA,
itemB,
itemC
),
),
)
Something like this during treatment of your request :
if (!array_key_exists($row['primary'], $final)) {
$final[$row['primary']] = array();
}
if (!array_key_exists($row['sub'], $final[$row['primary']])) {
$final[$row['primary']][$row['sub']] = array();
}
$final[$row['primary']][$row['sub']][] = $row['item'];
Something like this....
$final =
array(
'Primary1'=>array(
'Sub1'=>array("Item1", "Item2"),
'Sub2'=>array("Item3", "Item4")
),
'Primary2'=>array(
'Sub3'=>array("Item5", "Item6"),
'Sub4'=>array("Item7", "Item8")
),
);
You can do it using array_push but it's not that easy since you really want an associative array and array_push doesn't work well with keys. You could certainly use it to add items to your sub-elements
array_push($final['Primary1']['Sub1'], "Some New Item");
If I understand you correctly, you want to fetch a couple of db relations into an PHP Array.
This is some example code how you can resolve that:
<?php
$output = array();
$i = 0;
// DB Query
while($categories) { // $categories is an db result
$output[$i] = $categories;
$ii = 0;
// DB Query
while($subcategories) { // $subcategories is an db result
$output[$i]['subcategories'][$ii] = $subcategories;
$iii = 0;
// DB Query
while($items) { // $items is an db result
$output[$i]['subcategories'][$ii]['items'][$iii] = $items;
$iii++;
}
$ii++;
}
$i++;
}
print_r($output);
?>

get Order_Item_Id using magento api

I want to create invoice in to magento store using magento api in php.For that I want to create invoice for particular quantity and item means If anyone wants to invoice one item in paricular quantity then It shoud be done.My code is working for array() or all quantity.
Below is pseudo code for creating invoice
$client = new Zend_XmlRpc_Client('http://127.0.0.1:8080/AndroidMagento/api/xmlrpc')
$session = $client->call('login', array('tester','tester'));
$saleorderno = '100000007';
Mage::init();
$order = Mage::getModel('sales/order')->load($saleorderno);
$orderItems = $order->getAllItems();
$invoiceItems = array();
foreach ($orderItems as $_eachItem) {
$invoiceItems[$_eachItem->getItemId()] = $_eachItem->getQtyOrdered();
}
$result = $client->call('call',array($session,'sales_order_invoice.create',array($saleorderno,array('order_item_id' => 9474, 'qty' => 1),'Invoice Created by Test',false,false)));
I have seen this link where i found somewhat idea but i can't understand exactly.I can't understand how to get value of order_item_id.???
Any idea??? Please suggest me Thanks in advance...
item_id and product_id are different id.
order or quote has item_id and product_id.
You can try this:
$order = Mage::getModel('sales/order')->load($saleorderno);
$orderItems = $order->getAllItems();
foreach ($orderItems as $item){
print_r($item->getData());
print_r($item->getItemId()); //magic function to get ['item_id']
}
You can do it in 'sales/quote' Model.
Cheers ^^
Try this,
echo "<pre>";
$result = $client->call($session, 'sales_order.info', 'orderIncrementId');
print_r($result['item_id']);
print_r($result['product_id']);
and the $result will return all info of order including item_id and product_id,
with $result['item_id'] you can pass it to call
sales_order_invoice.create
then do
$result = $client->call(
$session,
'sales_order_invoice.create',
array('orderIncrementId' => '200000008',
array('order_item_id' => $result['item_id'],
'qty' => $result['total_qty_ordered'])
)
);
and the qty, You have to get it from $result['total_qty_ordered']
First, try to print_r[$result]; then You'll get some hints from it.
^^

having trouble getting sales for quarter

I'm trying to pull out the sales totals for quarter 1. I can't seem to get this to work. Any suggestions?
$total = 0;
$orders = Mage::getModel('sales_order/collection')
->addAttributeToSelect('*')
->addAttributeToFilter('created_at', array(
'from' => '2012-01-01',
'to' => '2012-03-31'));
foreach ($orders as $order) {
$total += $order->getGrandTotal();
}
echo $total;
You're not getting the collection properly. There are multiple ways to do this, looks like you might've combined a couple methods:
Mage::getModel('sales/order')->getCollection() or
Mage::getResourceModel('sales/order_collection')
However, if all you really want is to sum the single attribute grand_total it is way more efficient to build your own query rather that loading the entire sales order collection:
$db = Mage::getSingleton('core/resource')->getConnection('core_read');
$salesTable = Mage::getSingleton('core/resource')->getTableName('sales/order');
list($total) = $db->fetchCol(
$db->select()
->from($salesTable, array('grand_total' => 'SUM(grand_total)'))
->where('DATE(created_at) >= ?', '2012-01-01')
->where('DATE(created_at) <= ?', '2012-03-31')
);
echo $total;

Categories