Load a multidimensional array from 2 database queries and 2 loops - php

I am try to get a row of rep names as column headings and then under that heading the top ten sales items per that rep
I am try to get data to output like this:
RepName1 RepName2 RepName3 RepName4
(rep names come from Database and will never be a set number)
Underneath each rep name in the column their top ten selling items in descending order
Like so:
RepName1
(top selling info will be pulled from database)
1st selling item
2nd selling item
3rd selling item
4th selling item
5th selling item
6th selling item
7th selling item
8th selling item
9th selling item
10th selling item
Then start a new column with the next rep and his or her top ten sellers.
$qry = "SELECT sales_rep_login FROM sales_reps WHERE status = 'A'";
$return_reps = mysql_query($qry);
$reps = array();
while($repX = mysql_fetch_assoc($return_reps)) {
$reps[] = $repX['sales_rep_login'];
}
foreach ($reps as $rep){
$q="SELECT sales_quantity.style_num, sales_quantity.number_sold, sales_reps.fname, sales_reps.lname FROM catalog JOIN sales_quantity ON catalog.style_num = sales_quantity.style_num
JOIN sales_reps ON sales_quantity.sales_rep_login = sales_reps.sales_rep_login
WHERE catalog.status = 'A'
AND catalog.season_id = '" . $_POST['season'] . "'
AND sales_quantity.sales_rep_login = '" .$rep. "'
AND sales_reps.status = 'A'
ORDER BY sales_quantity.number_sold DESC LIMIT 10";
$return_sales = mysql_query($q);
$Total_Sales = array();
while($Sales=mysql_fetch_assoc($return_sales))
$Total_Sales[] = $Sales;
} // end foreach
for some reason I am only getting the info for the very last rep.
Thanks in advance

You are overwriting $total_Sales array. Define it before foreach.
$Total_Sales = array(); // define array here
foreach ($reps as $rep){
$q="SELECT sales_quantity.style_num, sales_quantity.number_sold, sales_reps.fname, sales_reps.lname FROM catalog JOIN sales_quantity ON catalog.style_num = sales_quantity.style_num
JOIN sales_reps ON sales_quantity.sales_rep_login = sales_reps.sales_rep_login
WHERE catalog.status = 'A'
AND catalog.season_id = '" . $_POST['season'] . "'
AND sales_quantity.sales_rep_login = '" .$rep. "'
AND sales_reps.status = 'A'
ORDER BY sales_quantity.number_sold DESC LIMIT 10";
$return_sales = mysql_query($q);
while($Sales=mysql_fetch_assoc($return_sales))
$Total_Sales[$rep][] = $Sales; // make 2 dimensional array
}
Print $Total_Sales and see it it has all the values.
Use mysqli instead of mysql which is depreciated.
Considering the result array as
$Total_Sales = array
(
'RepName1' => array(
array('names' => '1st selling item','style' => 'DD39050BG','num' => '660'),
array('names' => '2nd selling item','style' => 'DD39043','num' => '600'),
array('names' => '3rd selling item','style' => 'DD79021','num' => '582')
),
'RepName2' => array(
array('names' => '1st selling item','style' => 'DD39050BG','num' => '660'),
array('names' => '2nd selling item','style' => 'DD39043','num' => '600'),
array('names' => '3rd selling item','style' => 'DD79021','num' => '582')
),
'RepName3' => array(
array('names' => '1st selling item','style' => 'DD39050BG','num' => '660'),
array('names' => '2nd selling item','style' => 'DD39043','num' => '600'),
array('names' => '3rd selling item','style' => 'DD79021','num' => '582')
),
);
Use the below code to display
<table cellpadding="5" cellspacing="5" border="1 sold #ccc">
<tr>
<?php foreach($Total_Sales as $key=>$value){
echo "<td>".$key;
if(is_array($value) && count($value)>0){
echo "<table>";
foreach($value as $k=>$v){
echo "<tr><td>".$v['names']."</td></tr>";
}
echo "</table>";
}
echo "</td>";
}?>
</tr>
</table>

Related

PHP sort array of books into array of locations

I have an array of pickers assigned to locations there could be a varying number of these.
['picker A'=>'location 1','picker B'=>'location 2','picker C' => 'location 2', 'picker D'=>'location 1']
and an array of orders which can contain products in one or more locations I have sorted the orders products into separate location arrays already by looping through all orders and products and sorting them into separate locations based on the order products subArray so one order can exist across more then one location but only contain the products in that location if that makes sense.
location 1 orders...
locatinOneOrders[0] => ['order_id','customer name','products'=>['array of products in location 1']
locatinOneOrders[1] => ['order_id','customer name','products'=>['array of products in location 1']
location 2 orders..
locatinTwoOrders[0] => ['order_id','customer name','products'=>['array of products in location 2']
locatinTwoOrders[1] => ['order_id','customer name','products'=>['array of products in location 2']
locatinTwoOrders[2] => ['order_id','customer name','products'=>['array of products in location 2']
locatinTwoOrders[3] => ['order_id','customer name','products'=>['array of products in location 1']
What I need to do is assign an equal or as equal as possible number of orders to each picker based on the location.
So in the above example Picker A and Picker D should get one order each and Picker B and Picker C should get 2 orders each, this needs to work for any number of pickers per location and any number of orders.
Could be something as simple as the following using array_chunk.
<?php
$pickers = ['picker A'=>'location 1','picker B'=>'location 2','picker C' => 'location 2', 'picker D'=>'location 1'];
$pickersByLocation = [];
foreach ($pickers as $k => $v) {
$pickersByLocation[$v][] = $k;
}
$locationOneOrders = array_fill(0, 101, 'This is an order'); //some dummy order data
$dividedOrdersLocationOne = array_chunk($locationOneOrders, count($locationOneOrders) / count($pickersByLocation['location 1']));
foreach ($pickersByLocation['location 1'] as $k => $v) {
echo "Picker {$v} assigned: \n";
print_r($dividedOrdersLocationOne[$k]);
}
/*
Picker picker A assigned:
Array
(
[0] => This is an order
[1] => This is an order
...
Picker picker D assigned:
Array
(
[0] => This is an order
[1] => This is an order
...
You might end up with a chunk that is the remainder if numbers are odd. Handle that how you like.

How to sum all the current product prices of a user cart together as total price

I'm working on an Online Store project using PHP and MySQLi. Most of this project is done and now I'm struggling with total price that a user must pay. This total price is showing in the cart.php page (where users can see all the product items that they have added earlier). So it must be set to the total price of all current items.
So here is the code of cart.php:
if(isset($_GET['cart_id']))
{
$cart_id = $_GET['cart_id'];
$get_add = "SELECT * FROM cart WHERE cart_id = '$cart_id'";
$run_add = mysqli_query($con,$get_add);
$cart_items = [];
while ($row_results = mysqli_fetch_array($run_add)){
$item = array(
'table_id' => $row_results['table_id'],
'cart_id' => $row_results['cart_id'],
'pro_id' => $row_results['product_id'],
'pro_title' => $row_results['product_title'],
'pro_price' => $row_results['product_price'],
'pro_img' => $row_results['product_image'],
'pro_supplier' => $row_results['product_supplier'],
'qty' => $row_results['qty'],
'cart_ip' => $row_results['cart_ip'],
);
$cart_items[] = $item;
}
foreach ($cart_items as $cart) {
echo $cart['pro_price']
}
}
The table cart structure goes like this:
see image here
So now I want to print the sum of all products as total_price, till now I tried several different ways but I could not get the result.
So if you know how to solve this question, please let me know.. I really really appreciate that...
Thanks in advance!
Assuming you need the sum of qty*product_price you could sum this way
$tot = 0;
while ($row_results = mysqli_fetch_array($run_add)){
$cart_items[] = array(
'table_id' => $row_results['table_id'],
'cart_id' => $row_results['cart_id'],
'pro_id' => $row_results['product_id'],
'pro_title' => $row_results['product_title'],
'pro_price' => $row_results['product_price'],
'pro_img' => $row_results['product_image'],
'pro_supplier' => $row_results['product_supplier'],
'qty' => $row_results['qty'],
'cart_ip' => $row_results['cart_ip'],
);
$tot += $row_results['qty']*$row_results['product_price'];
}
foreach ($cart_items as $cart) {
echo $cart['pro_price'];
}
echo $tot;

Create array from mysql query

I have something like this in my MySQL DB.
Date product
2015-01-01 1
2015-01-01 2
2015-02-03 3
2015-02-04 1
2015-02-04 1
2015-02-04 3
What i need in PHP is to know which product was how often sold on which day.
So: 01.01.2015 Product 1 one time, product 2 one time, on 04.02.2015 product 1 two times, product 3 one time ...
Like this:
Date product 1 product 2 product 3
2015-01-01 1 1 0 //how many times
2015-02-03 0 0 1
2015-02-04 2 0 1
So i did a normal query: SELECT date from table order by date.
I get the object as stdClass in a array back, but now i am stuck with how to get the information out i need.
I tried something like
$array=array();
foreach ($result as $key => $value) {
$time = ($result[$key]->date);
$temp[] = array(
'date' => $time,
'product 1' => '2', //equals times
'product 2' => '3',
'product 3' => '4',
'product 4' => '4'
);
$arrayBig[] = $temp;
}
And also used array_count_values to filter the days to know which days appears, but i can not find out how to connect the product to the days.
EDIT: DWright's solution:
SELECT product, date, COUNT(*)
FROM tablename
GROUP BY product, date.
Date product count(*)
2015-01-01 1 1
2015-01-01 2 2
2015-02-03 3 1
Worked fine, now i have in each row which product was sold in which date how often.
The problem i encounter now is that if i want use this data to populate google stacked charts as seen below each row in the results represents on column in the google charts graph. So for the example above i will have two entries on 01.01.2015 in my charts (one bar for product 1 and one for product 2) but i want the amount of products on each day to be stacked. So there should be only one entry for 01.01.2015 where the amount of product 1 sold on that day and the amount of product 2 sold that day is stacked onto each other,
$result = $sql statement
foreach ($result as $key => $value ) {
$typeOfProduct = $value->product;
$amount = $value->anzahl;
$time = $value->Date;
switch ($typeOfProduct) {
case 1:
$produt1 = $amount;
break;
case 2: //twitter
$product2 = $amount;
break;
case 3:
$product3 = $amount;
break;
default:
break;
}
$rows = array();
$table = array();
$table['cols'] = array(
array('label' => 'Datum', 'type' => 'date'),
array('label' => 'product 1', 'type' => 'number'),
array('label' => 'product 2', 'type' => 'number'),
array('label' => 'product 3', 'type' => 'number')
);
$day = date('d', strtotime( $time ) );
$month = date('m', strtotime( $time ) );
$monthNew = $month - 1;
$year = date('Y', strtotime( $time ) );
$temp[] = array('v' => "Date( $year, $monthNew, $day )");
$temp[] = array('v' => $product1 );
$temp[] = array('v' => $product2);
$temp[] = array('v' => $product3 );
$rows[] = array('c' => $temp);
$table['rows'] = $rows;
}
This would result in something like this:https://jsfiddle.net/api/post/library/pure/
But i would need the values to be stacked onto each other , like this:
https://jsfiddle.net/api/post/library/pure/
This will be a lot easier for you to do in SQL. Something like:
SELECT product, date, COUNT(*)
FROM tablename
GROUP BY product, date.
Then each row is for one product by date, with the count sold that date.

Magento Sales Order Invoice with product quantity updation using API not working properly

I'm creating a Magento application and I'm planing to create sales order invoice by using Magento API.
Here is my pseudo code for my invoice creation. The problem is it creates an invoice but that invoice is always blank (not showing products and quantity)
<?php
$proxy = new SoapClient('http://myurl/api/soap?wsdl');
$sessionId = $proxy->login('apiuser', 'apikey');
// item array with sku and quantity
$invoiceItems = array(
'002' => '1', '003' => '1', '004' => '1', '005' => '1'
);
// Create new invoice
$newInvoiceId = $proxy->call($sessionId, 'sales_order_invoice.create', array($saleorderno, $invoiceItems, 'Invoice Created', true, true));
?>
But when I'm creating an sales order invoice like this (there's no changes in quantity from sales order), it works properly
$newInvoiceId = $proxy->call($sessionId, 'sales_order_invoice.create', array($saleorderno, array(), 'Invoice Created', true, true));
Is there any mistakes with my code?
Can any one give some advice for me?
In the array variable "$invoiceItems", you are providing this value:-
$invoiceItems = array(
'002' => '1',
'003' => '1',
'004' => '1',
'005' => '1'
);
The keys for the above array must correspond to the Order Item ID and not to the Item SKU. This means that whenever an order is placed, each ordered item get its own unique Order Item ID, which is not at all same as that of the corresponding SKU or the corresponding Product ID.
So to get this, you need to load the Order Collection from the Order ID, and fetch the Items Collection list as below:-
$saleorderno = 'SOME VALID ORDER INCREMENT ID';
$order = Mage::getModel('sales/order')->loadByIncrementId($saleorderno);
$orderItems = $order->getAllItems();
$invoiceItems = array();
foreach ($orderItems as $_eachItem) {
$invoiceItems[$_eachItem->getItemId()] = $_eachItem->getQtyOrdered();
}
$newInvoiceId = $proxy->call($sessionId, 'sales_order_invoice.create', array($saleorderno, $invoiceItems, 'Invoice Created', true, true));

PHP: Incremental list using SESSION?

I'm working on a simple shopping cart, I'm able to output a single form result (POST), but I have no idea how to incrementaly add lines to newer items when the user comes back to the form and adds items (they are currently being overriden).
Here's what I currenly have:
<?php
session_start();
//Getting the list
$list[]= $_SESSION['list'];
$_SESSION['list'] = array(
'item' => $item,
'quantity' => $quantity,
'price' => $price);
//list
echo "<b>SHOPPING CART</b></br>";
echo "1. ".$_SESSION['list']['item']." ".$_SESSION['list']['quantity']." units".", ".$_SESSION['list']['price']." USD.";
//Returning list
$_SESSION['list'] = $list;
?>
A sample of the current output is:
SHOPPING CART
1. Banana 3 units, 2 USD.
The ideal output should be something like this:
SHOPPING LIST
1. Banana 3 units, 2 USD.
2. Coffe 4 units, 6 USD.
3. Etc
and infinte...
Let it be a multi-dimensional array:
//add an element to the list
$_SESSION['list'][] = array(
'item' => $item,
'quantity' => $quantity,
'price' => $price),
);
Then use foreach to loop over it:
foreach($_SESSION['list'] as $key => $item) {
echo $key, '. ', $item['item'], ' ', $item['quantity'], ' units';
}

Categories