How to set calculate items of loop in one array in PHP - php

Following is my array
(
[0] => Array
(
[items] => 10.4
[Total] => 10.4
)
[1] => Array
(
[items] => 10.5
[Total] => 10.5
)
[2] => Array
(
[items] => 4.5
[Total] => 15
)
[3] => Array
(
[items] => 15.2
[Total] => 15.2
)
[4] => Array
(
[items] => 8.4
[Total] => 8.4
)
)
Here each array has items & total , I want to check if total of each item is less then 20 then set items with total in a array and also not check already checked item.
For example there are 4 items in array 0 has item 10.4 & total 10.4 then check is less then 20 if not then plus second array item means (10.4 + 10.5) again check if is greater then 20 If yes then set last checked in array like array('item'=>10.4, 'total'=>10.4) , Now second time 10.4 item will skip & check with 10.5 + 4.5 etc...
I want output like.
(
[0] => Array
(
[items] => array([0]=>10.4),
[Total] => 10.4
)
[1] => Array
(
[items] => array(
[0] => 10.5,
[1] => 4.5
),
[Total] => 15
)
[2] => Array
(
[items] => array([0]=>15.2)
[Total] => 15.2
)
[3] => Array
(
[items] => array([0]=>8.4)
[Total] => 8.4
)
)
Following is my script.
$packageInfo = $ordercon->get_package_items_by_order_number($order_number); // Comes from model
// First calculate the total
foreach ($packageInfo as $key => $package) {
$packageInfo[$key]['total_weight'] = $package['quantity'] * $package['weight'];
$packageInfo[$key]['currnt_item'] = $package['quantity'] * $package['weight'];
}
// Then check count the packages ?
$packages = [];
$packageTotalWeight = 0;
$packageItemWeight = 0;
foreach ($packageInfo as $key => $package) {
if(($packageTotalWeight + $package['total_weight']) > 20){
$packages[]['final_total'] = $packageTotalWeight;
$packageTotalWeight = $package['total_weight'];
$data[] = array('items'=>$package['currnt_item'], 'Total'=>$packageTotalWeight); // For combine items
} else {
$packages[]['currntItem'] = $package['quantity'] * $package['weight'];
$packageTotalWeight += $package['total_weight'];
$data[] = array('items'=>$package['currnt_item'], 'Total'=>$packageTotalWeight);
}
}
echo "<pre>";print_r($data);
echo '<pre>packageInfo';print_r($packageInfo);

Related

PHP push missing weekdays with 0 total into array

I need to buildup a graph with total sales for each day for last week, I did not get all 7 days data, rather getting 3 days data from database, I need to push rest of the 4days with total sales 0,
I have the following array of 3 days
Array
(
[0] => Array
(
[SalesDate] => Jun09
[total] => 4
)
[1] => Array
(
[SalesDate] => Jun11
[total] => 2
)
[2] => Array
(
[SalesDate] => Jun14
[total] => 1
)
)
but I need all 7days data from Jun09 to Jun15 like this
Array
(
[0] => Array
(
[SalesDate] => Jun09
[total] => 4
)
[1] => Array
(
[SalesDate] => Jun10
[total] => 0
)
[2] => Array
(
[SalesDate] => Jun11
[total] => 2
)
[3] => Array
(
[SalesDate] => Jun12
[total] => 0
)
[4] => Array
(
[SalesDate] => Jun13
[total] => 0
)
[5] => Array
(
[SalesDate] => Jun14
[total] => 1
)
[6] => Array
(
[SalesDate] => Jun15
[total] => 0
)
)
I have tried with following code, but not getting the required data.
<?php
$sales =array(array('SalesDate' => 'Jun09',
'total' => 4
),
array
(
'SalesDate' => 'Jun11',
'total' => 2
),
array
(
'SalesDate' => 'Jun14',
'total' => 1
)
);
$final_array = array();
foreach($sales as $sale)
{
for($i=7;$i>0;$i--)
{
$current_weeks =[];
if($sale['SalesDate'] ==date('Md', strtotime("-".$i." days")))
{
$week_days['SalesDate'] = $sale['SalesDate'];
$week_days['total'] = $sale['total'];
}
else
{
$week_days['SalesDate'] = date('Md', strtotime("-".$i." days"));
$week_days['total'] = 0;
}
$final_array[] =$week_days;
}
}
You could first create a 'skeleton' array that matches your source array $arr, but with all the previous seven days $prevSevenDays. The date format matches the source array's, the totals are all set to 0.
// build empty skeleton
$prevSevenDays = [];
for ($i = 7; $i > 0; $i--) {
$prevSevenDays[$i]['SalesDate'] = date('Md', strtotime("-$i days"));
$prevSevenDays[$i]['Total'] = 0;
}
All you have to do is cycle through this array to replace the entries with available data in your source array $arr.
foreach ($arr as $sales) {
foreach ($prevSevenDays as $key => $day) {
if ($sales['SalesDate'] === $day['SalesDate']) $prevSevenDays[$key]['Total'] = $sales['Total'];
}
}
demo

Determine Taker Price from Bid/Ask Order Book

I am working on a bitcoin trading script in PHP. To run paper trading on live data, I have to determine buy/sell price from order book i.e taker price.
Order book live json data looks like this
Order book has two main arrays - bids & asks. Each bid/ask array has price [0], quantity [1] and the third parameter [2] is irrelevant:
Bid/Ask Sample Array
[0] => Array
(
[0] => 8848.99
[1] => 9.89850469
[2] => 7
)
[1] => Array
(
[0] => 8848.2
[1] => 0.05
[2] => 1
)
[2] => Array
(
[0] => 8848.02
[1] => 0.274203
[2] => 1
)
[3] => Array
(
[0] => 8848.01
[1] => 0.0012
[2] => 1
)
[4] => Array
(
[0] => 8847.47
[1] => 0.5
[2] => 1
)
[5] => Array
(
[0] => 8846.99
[1] => 0.28345
[2] => 1
)
[6] => Array
(
[0] => 8846.81
[1] => 0.75
[2] => 1
)
[7] => Array
(
[0] => 8846
[1] => 0.75181214
[2] => 2
)
[8] => Array
(
[0] => 8845.99
[1] => 26.57694043
[2] => 28
)
From the above data, how to calculate average price for 15 or n number of coins in PHP? Considering that orders will be filled/taken from top to bottom as available.
I solved it with this Excel formula:
Avg. Cost = sumproduct(price series, qty series) / sum(qty series)
Here is the PHP code:
$order_book = json_decode($order_book, true);
$bids = ($order_book['bids']);
$ordered = 15; //n number of coins
$filled = 0;
$fill_array = array();
foreach ($bids as $PriceQty) {
$price = $PriceQty[0];
$qty = $PriceQty[1];
if ($ordered != $filled){
$required = $ordered - $filled;
if ($qty >= $required){
$fill_array[] = array($price,$required);
$filled = $filled + $required;
break;
}else{
$filled = $filled + $qty;
$fill_array[] = array($price,$qty);
}
}
}
$totalQty = 0;
$totalSum = 0;
foreach ($fill_array as $PriceQty) {
$totalSum = $totalSum + ($PriceQty[0] * $PriceQty[1]);
$totalQty = $totalQty + $PriceQty[1];
}
echo "$totalSum/$totalQty = ".($totalSum/$totalQty);
There might be simpler way of doing this, someone could improve this answer. For now it produces expected average.

Combine and sum values in multi-dimensional associative array using php

I have an associative array that looks like this:
Array (
[0] => Array (
[amount] => 3
[name] => Chuck
)
[1] => Array (
[amount] => 2
[name] => Steve
)
[2] => Array (
[amount] => 5
[name] =>
)
[3] => Array (
[amount] => 4
[name] => Chuck
)
[4] => Array (
[amount] =>
[name] => Chuck
)
)
I need to remove values that are missing a name or amount e.g. [2] and [4] and then sum the totals for each name so that the final array is:
Array (
[0] => Array (
[amount] => 7
[name] => Chuck
)
[1] => Array (
[amount] => 2
[name] => Steve
)
)
For anyone looking for this nowadays, this would be much cleaner:
$sum = array_sum(array_column($data, 'amount'));
Try this:
$starting_array = array( ... ); // Initial array with your setup
$final_array = array();
$sum = 0;
foreach ($starting_array as $idx => $data) {
if (!empty($data['amount']) && !empty($data['name'])) {
$final_array[$idx] = $data;
$sum += $data['amount'];
}
}
// After looping through all of the items, $final_array should contain all
// of the specific items that have an amount and name set. In addition, the
// total of all of the amounts will be in $sum.
Take a look at php's empty(). Note: If 0 is an allowed value, you may want to use is_null() instead.

php loop array and update

I have an array and I wish to update the values in roomTotalPrice. However when I loop, it changes to just a variable.
Array I want to change:
Array
(
[10] => Array
(
[12] => Array
(
[num_rooms] => 2
[adults] => Array
(
[0] => 2
[1] => 2
)
[prices] => Array
(
[0] => 44.5
[1] => 44.5
)
[roomTotalPrice] => Array
(
[0] => 44.5
[1] => 44.5
)
[price] => 178
[supp] => 0
)
)
Code I am using:
//Total Room Price
foreach($iroom['roomTotalPrice'] as $irt){
$s_rate[$iraid][$iroid]['roomTotalPrice'] = 100;
}
Array
(
[10] => Array
(
[12] => Array
(
[num_rooms] => 2
[adults] => Array
(
[0] => 2
[1] => 2
)
[prices] => Array
(
[0] => 44.5
[1] => 44.5
)
[roomTotalPrice] => 100
[price] => 178
[supp] => 0
)
)
Use this code:
foreach($iroom['roomTotalPrice'] as &$irt){
$irt = 100;
}
Anyway this code is based on the fact that $iroom['roomTotalPrice'] loop on the right sub-array as you have written.
Are you trying to make the sum for prices ?
$x[10][12][roomTotalPrice] = array_sum($x[10][12][roomTotalPrice])
Assuming that the $iroom variable is the array in your first code sample, I believe you can use the following code to set all 'roomTotalPrice' entries to 100:
foreach ($iroom as $firstLevelIndex => $firstLevelArray) {
foreach ($firstLevelArray as $secondLevelIndex => $secondLevelArray) {
$iroom[$firstLevelIndex][$secondLevelIndex]['roomTotalPrice'] = 100;
}
}
Is this what your want?
foreach ($iroom as $k1 => $v1) { // Loop outer array
foreach ($v1 as $k2 => $v2) if (isset($v2['roomTotalPrice'])) { // Loop inner arrays and make sure they have a roomTotalPrice key
foreach ($v2['roomTotalPrice'] as $k3 => $v3) { // Loop roomTotalPrice array
$iroom[$k1][$k2]['roomTotalPrice'][$k3] = 100; // Change the values
}
}
}

php loop array to get total

I am having some difficulty looping through an array and calculating fields. Here is the array $iroom:
Array
(
[num_rooms] => 2
[adults] => Array
(
[0] => 2
[1] => 2
)
[prices] => Array
(
[0] => 44.5
[1] => 44.5
)
[roomTotalPrice] => Array
(
[0] => 89
[1] => 89
)
[price] => 178
)
I want to (adults*prices)+(adults*$asup)+(chidern*$csup)+$ssup and pu the answer into the roomTotalPrice. So far the outer forloop sets the roomTotalPrice price but I cannot get the inner loops to calculate the price. The $sup are extra supplement prices.
The code I got so far:
foreach($iroom['roomTotalPrice'] as &$irt){
foreach($iroom['adults'] as $ira){
}
$irt = ;
}
CODE WRAPPED IN FUNCTION, TO HANDLE NEW ARRAY FORMAT
/*
Note that this function may not be 100% correct. I notice you have removed
the 'supp' key from the array, and that your current spec doesn't do anything
with the 'price' key. I suspect you may want the line
+ ((isset($array['supp'])) ? $array['supp'] : 0);
to read
+ ((isset($array['price'])) ? $array['price'] : 0);
*/
function calculateTotalPrices ($array, $asup = 10, $csup = 10) {
if (!is_array($array) || !isset($array['num_rooms']) || !$array['num_rooms']) return FALSE; // make sure data is valid
for ($i = 0; $i < $array['num_rooms']; $i++) { // Loop num_rooms times
$array['roomTotalPrice'][$i] =
((isset($array['adults'][$i],$array['prices'][$i])) ? ($array['adults'][$i] * $array['prices'][$i]) + ($array['adults'][$i] * $asup) : 0) // Calculate price for adults
+ ((isset($array['childern'][$i])) ? ($array['childern'][$i] * $csup) : 0) // Calculate price for children
+ ((isset($array['supp'])) ? $array['supp'] : 0); // Add the supplement
}
// Get a total price for adults + children + supplements for all rooms
$array['grandTotal'] = array_sum($array['roomTotalPrice']);
return $array;
}
$iroom = array (
'num_rooms' => 2,
'adults' => array (
0 => 2,
1 => 3
),
'childern' => array (
0 => 1,
1 => 2
),
'prices' => array (
0 => 44.5,
1 => 44.5
),
'price' => 178,
);
print_r(calculateTotalPrices($iroom));
/* With the above array, outputs
Array
(
[num_rooms] => 2
[adults] => Array
(
[0] => 2
[1] => 3
)
[childern] => Array
(
[0] => 1
[1] => 2
)
[prices] => Array
(
[0] => 44.5
[1] => 44.5
)
[price] => 178
[roomTotalPrice] => Array
(
[0] => 119
[1] => 183.5
)
[grandTotal] => 302.5
)
*/
print_r(calculateTotalPrices($iroom,20,25));
/* With your sample array, outputs
Array
(
[num_rooms] => 2
[adults] => Array
(
[0] => 2
[1] => 3
)
[childern] => Array
(
[0] => 1
[1] => 2
)
[prices] => Array
(
[0] => 44.5
[1] => 44.5
)
[price] => 178
[roomTotalPrice] => Array
(
[0] => 154
[1] => 243.5
)
[grandTotal] => 397.5
)
*/
CODE UPDATED WITH ADDITIONAL CHECKS
foreach ($iroom as $k1 => $v1) { // Loop outer array
if (is_array($v1)) { // Make sure element is an array
foreach ($v1 as $k2 => $v2) { // Loop inner array
if (is_array($v2)) { // Make sure element is an array
for ($i = 0; $i < $v2['num_rooms']; $i++) { // Loop num_rooms times
$iroom[$k1][$k2]['roomTotalPrice'][$i] =
((isset($v2['adults'][$i],$v2['prices'][$i])) ? ($v2['adults'][$i] * $v2['prices'][$i]) + ($v2['adults'][$i] * $asup) : 0) // Calculate price for adults
+ ((isset($v2['childern'][$i])) ? ($v2['childern'][$i] * $csup) : 0) // Calculate price for children
+ $v2['supp']; // Add the supplement
}
// Get a total price for adults + children + supplements for all rooms
$iroom[$k1][$k2]['grandTotal'] = array_sum($iroom[$k1][$k2]['roomTotalPrice']);
}
}
}
}
print_r($iroom);
EDIT
Using the exact code above, feeding in the array above, and setting $asup = $csup = 10; at the top, I get no errors, and this output:
Array
(
[10] => Array
(
[12] => Array
(
[num_rooms] => 2
[adults] => Array
(
[0] => 2
[1] => 3
)
[childern] => Array
(
[0] => 1
[1] => 2
)
[prices] => Array
(
[0] => 44.5
[1] => 44.5
)
[price] => 178
[supp] => 0
[roomTotalPrice] => Array
(
[0] => 119
[1] => 183.5
)
[grandTotal] => 302.5
)
)
)
Note that the first result comes out at 119, not 129 as you state in the comment above - this is because in your example array, supp is 0 and not 10, as you have used in your calculation.
I have also tested with more complex arrays (with more elements at the first and second levels) and it works fine.
I'm guessing if you are getting "invalid argument supplied for foreach" errors it's because in your actual array, you highest level has some non-array memebers. This can easily be overcome by changing
foreach ($v1 as $k2 => $v2) {
to
if (is_array($v1)) foreach ($v1 as $k2 => $v2) {

Categories