How to get array values and add up total - php

So what I want to do is get all values from query and add them together to get a total amount. The following function grabs all values necessary. (Added for clarity)
public function priceTotal($conn, $var, $hours){
$query = "SELECT hour_rate, day_rate, item_id, hourly_rental FROM products WHERE item_id = :id";
$stmt = $conn->prepare($query);
$stmt->bindParam(":id", $var);
$stmt->execute();
$result = $stmt->fetchAll();
if($stmt->rowCount() > 0){
$total = 0;
foreach($result as $row){
$hour_rate = $row['hour_rate'];
$day_rate = $row['day_rate'];
if($hours == '2'){
$total += $hour_rate;
}else{
if($row['hourly_rental'] == '1'){
$hours -= 2;
$total += $hour_rate + $day_rate * $hours;
}
else{
$total = $hour_rate + $day_rate;
}
}
$array[] = $total;
}
return $array;
}
return false;
}
Now what I need to be able to do is grab the values from the array and add them all together. This was my latest attempt. But only the items in the last array get added together.
$weeklyGross = $chart->getChartInfo($conn, $weekly);
if(!empty($weeklyGross)){
foreach($weeklyGross as $row){
$hours = $row['total_hours'];
$totalItems = $row['requested_items'];
$delivery_cost = $row['delivery_cost'];
//Store total items in array
$items = explode(',', $totalItems);
$item_name = array();
$totalPrice = 0;
foreach ($items as $var){
//Get items from price total function
$addItems = $chart->priceTotal($conn, $var, $hours);
//$completeOrder = array_merge($addItems);
print_r($addItems);
foreach($addItems as $k){
$totalPrice += $k;
}
}
$totalPrice += $delivery_cost;
}
print_r($totalPrice);
}
Here is the printout of the arrays, and the values that I would like to add all together.
Array (
[0] => 420
[1] => 200
)
Array (
[0] => 270
)
Array (
[0] => 350
[1] => 350
)
Array (
[0] => 270
)
Array (
[0] => 220
)
Array (
[0] => 280
)
Array (
[0] => 270
[1] => 300
)
Array (
[0] => 700
[1] => 380
)

See what I have done with $totalPrice
$weeklyGross = $chart->getChartInfo($conn, $weekly);
if(!empty($weeklyGross)){
$totalPrice = 0; // << Put this here
foreach($weeklyGross as $row){
$hours = $row['total_hours'];
$totalItems = $row['requested_items'];
$delivery_cost = $row['delivery_cost'];
//Store total items in array
$items = explode(',', $totalItems);
$item_name = array();
/// $totalPrice = 0; // << not here, as it resets the total price on each loop
foreach ($items as $var){
//Get items from price total function
$addItems = $chart->priceTotal($conn, $var, $hours);
//$completeOrder = array_merge($addItems);
print_r($addItems);
foreach($addItems as $k){
$totalPrice += $k;
}
}
$totalPrice += $delivery_cost;
}
print_r($totalPrice);
}

Related

Create an array from two array PHP

i have two arrays
$value_array = array('50','40','30','20','10');
$customer = array('300','200','100');
i want to distribute the value array to customers based on the value of customers that is taken as limit.adding values by checking it wont cross the limit that is 300 , 200 and 100.
but customer array not working one direction it should work first forward and then backward like that
i want to produce an array in form of
Array
(
[0] => Array
(
[0] => 50
)
[1] => Array
(
[0] => 40
[1] => 10
)
[2] => Array
(
[0] => 30
[1] => 20
)
)
After completing customer loop first time it should start from last to first. both array count will change , i mean count.
value array should check 50 -> 300 , 40->200, 30->100 then from last ie, 20 ->100, 10->200 etc.
I tried like
$i = 0;
while($i < count($customer)){
foreach($value_array as $k=>$value){
$v = 0;
if($value <= $customer[$i]){
$customer2[$i][] = $value;
unset($value_array[$k]);
$v = 1;
}
if($v ==1){
break;
}
}
//echo $i."<br/>";
if($i == (count($customer)-1) && (!empty($value_array))){
$i = 0;
$customer = array_reverse($customer, true);
}
$i++;
}
echo "<pre>";
print_r($customer2);
$valueArray = array('50','40','30','20','10','0','-11');
$customer = array('300','200','100');
function parse(array $valueArr, array $customerArr)
{
$customerCount = count($customerArr);
$chunkedValueArr = array_chunk($valueArr, $customerCount);
$temp = array_fill(0, $customerCount, array());
$i = 0;
foreach ($chunkedValueArr as $item) {
foreach ($item as $key => $value) {
$temp[$key][] = $value;
}
$temp = rotateArray($temp);
$i++;
}
// if $i is odd
if ($i & 1) {
$temp = rotateArray($temp);
}
return $temp;
}
function rotateArray(array $arr)
{
$rotatedArr = array();
//set the pointer to the last element and add it to the second array
array_push($rotatedArr, end($arr));
//while we have items, get the previous item and add it to the second array
for($i=0; $i<sizeof($arr)-1; $i++){
array_push($rotatedArr, prev($arr));
}
return $rotatedArr;
}
print_r(parse($valueArray, $customer));
returns:
Array
(
[0] => Array
(
[0] => 50
[1] => 0
[2] => -11
)
[1] => Array
(
[0] => 40
[1] => 10
)
[2] => Array
(
[0] => 30
[1] => 20
)
)

How do I count the sum of specified sum in $total

e.g. if I pass $total = 2 then it should calculate the sum of first
two arrays.
sub1 + sub2
**HERE IS MY CODE **
<?php
$num = 2;
$array = array();
$total = 2;
for($x=1;$x<=$num;$x++)
{
$result = array('sub1'=>rand(1,100),
'sub2'=>rand(1,100),
'sub3'=>rand(1,100),
'sub4'=>rand(1,100),
'sub5'=>rand(1,100));
$array[] = $result;
}
echo '<pre>'; print_r($array);
?>
try
<?php
$array = array();
$total = 2;
$result = array('sub1'=>rand(1,100),
'sub2'=>rand(1,100),
'sub3'=>rand(1,100),
'sub4'=>rand(1,100),
'sub5'=>rand(1,100));
$temp_array = array_slice($result, 0, $total);
$sum = array_sum($temp_array);
print_r($result);
echo "sum of $total array is : ".$sum;
Output would be like :
Array
(
[sub1] => 30
[sub2] => 19
[sub3] => 56
[sub4] => 47
[sub5] => 6
)
sum of 2 array is : 49
https://eval.in/539097
should do the trick. hope it helps :)
simply you can use for loop like this
$sum=0;
for($i=0;$i<$total;$i++){
$sum+=$result[$i];
}

Multidimensional array sum values

I have following function to sum multidimensional array values.
// summing values of multidimensional array
function getSum($array, $path = array()){
// process second argument:
foreach ($path as $key) {
if (!is_array($array) || !isset($array[$key])) {
return 0; // key does not exist, return 0
}
$array = $array[$key];
}
if(is_array($array)) {
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$sum = 0;
foreach ($iterator as $key => $value) {
$sum += $value;
}
} else{
$sum = $array;
}
return $sum;
}
I'm using the function like this:
$array = array();
$array['one']['green'][20] = 20;
$array['one']['blue'][20] = 5;
$array['one']['blue'][30] = 10;
getSum($array,['one','green']); // 20
getSum($array,['one','blue',20]); // 5
Now I have a problem if I don't want to for example set any spesific color because I want that script sums all values from category 20 from all colours.
So it should be working like this:
getSum($array,['one','*',20]); // 25
Thanks for your help!
Here is example of my array:
Array (
[1] => Array (
[AREA I] => Array (
[20] => 1
[25] => 0
[30] => 0 )
[AREA II] => Array (
[20] => 0
[30] => 0 )
[AREA III] => Array (
[20] => 2
[30] => 0 )
[AREA IV] => Array (
[20] => 0
[30] => 3 )
[AREA V] => Array (
[20] => 4
[25] => 0
[30] => 3 )
)
[2] => Array (
[AREA I] => Array (
[20] => 0
[30] => 0 )
[AREA II] => Array (
[20] => 0
[30] => 0 )
)
)
And here is example of my getSum call:
getSum($visitsandinfosact,['*','*',20]); // should print 7
Recursive Function
I was not sure if ['one','*'] should give 45 but if it should just return 0 you just have to remove the else if (empty($filterList) && is_array($value) && $first == "*")condition. All values which are not arrays are just converted to int via intval and added to the sum. If you wanna use float then use floatval instead of intval
function getSum($array, $filterList = array('*')) {
$sum = 0;
$first = array_shift($filterList);
foreach ($array as $key => $value) {
if ($key == $first || $first == "*") {
if (is_array($value) && !empty($filterList)) {
$sum += getSum($value, $filterList);
} else if (empty($filterList) && is_array($value)) {
$sum += getSum($value, array("*"));
} else if (empty($filterList)) {
$sum += intval($value);
}
}
}
return $sum;
}
echo getSum($array,['one','*',20], 10) . "\n"; // 25
echo getSum($array,['one','*','*',20]) . "\n"; // 10
echo getSum($array,['one','*']) . "\n"; // 45
echo getSum($array) . "\n"; // 45
Input Array
$array = array();
$array['one'] = array();
$array['one']['green'] = array();
$array['one']['green'][20] = 20;
$array['one']['blue'] = array();
$array['one']['blue'][20] = 5;
$array['one']['blue'][30] = 10;
$array['one']['orange']['red'][20] = 10;
Output
Only the numbers are outputted but just added the input params for better understanding.
25 // (['one','*',20])
10 // (['one','*','*',20])
45 // (['one','*'])
45 // no filterList
In short, you need a recursive function to add in wildcard "endpoints". You might as well use the same recursive nature to cover the addition as well.
The following should do what you're wanting:
// summing values of multidimensional array
function getSum(&$array, $path = array()){
$sum = 0;
if(is_int($array) and empty($path)) // return value if int
$sum = $array;
else if(is_array($array)){ // else add recurred values
if(empty($path)){
foreach($array as $value)
$sum += getSum($value);
} else {
$key = array_shift($path);
if($key=='*'){
foreach($array as $value)
$sum += getSum($value, $path);
} else {
if(isset($array[$key]))
$sum += getSum($array[$key], $path);
}
}
}
return $sum;
}
Test:
$array['one'] = array();
$array['one']['green'] = array();
$array['one']['green'][20] = 20;
$array['one']['blue'] = array();
$array['one']['blue'][20] = 5;
$array['one']['blue'][30] = 10;
$array['one']['orange']['red'][20] = 10;
echo getSum($array,['one','*',20]); // 25
echo getSum($array,['one','*','*',20]); // 10
echo getSum($array,['one','*']); // 45
Happy coding

Passed multidimensional array to view in codeigniter

I'm trying to create foreach statement using multidimensional array.
Controller:
function index()
{
$index1 = 0;
$index2 = 0;
$index3 = 0;
$index4 = 0;
$result1 = $this->data->get_test('kdprogram','kdprogram');
foreach($result1 as $row1){
$array_temp[$index1] = $row1;
$result2 = $this->data->get_test('kdgiat','kdgiat','kdprogram = '.$row1['kdprogram']);
foreach($result2 as $row2){
$array_temp[$index1][$index2] = $row2;
$result3 = $this->data->get_test('kdoutput','kdoutput','kdprogram = '.$row1['kdprogram'].' and kdgiat = '.$row2['kdgiat']);
foreach($result3 as $row3){
$array_temp[$index1][$index2][$index3] = $row3;
$result4 = $this->data->get_test('kdsoutput','kdsoutput','kdprogram = '.$row1['kdprogram'].' and kdgiat = '.$row2['kdgiat'] .' and kdoutput = '.$row3['kdoutput']);
foreach($result4 as $row4){
$array_temp[$index1][$index2][$index3][$index4] = $row4;
$index4++;
}
$index3 ++;
}
$index2 ++;
}
$index1 ++;
}
//print_r($array_temp);
$data['damn'] = $array_temp;
$this->load->view('report/laporan_output', $data);
}
$data contains:
Array
(
[0] => Array
(
[kdprogram] => 06
[0] => Array
(
[kdgiat] => 3400
[0] => Array
(
[kdoutput] => 001
[0] => Array
(
[kdsoutput] => 001
)
[1] => Array
(
[kdsoutput] => 006
)
)
[1] => Array
(
[kdoutput] => 008
[2] => Array
(
[kdsoutput] => 001
)
)
)
)
)
How to echo each array (kdprogram, kdgiat, etc) on view especially with html table?
Am i doing it right?
Thanks
it looks kinda ugly and i would use some sort of recursive function but here is your way
in controller ( i assume the arrays have numeric index otherwise you have to use some sort of counter like you did in your code )
foreach($result1 as $a_counter=>$row1)
{
$array_temp[$a_counter] = array( 'parent'=>$row1 , 'child'=>array());
$result2 = $this->data->get_test('kdgiat','kdgiat','kdprogram = '.$row1['kdprogram']);
foreach($result2 as $b_counter=> $row2)
{
$array_temp[$a_counter]['child'][$b_counter] = array( 'parent'=>$row2 , 'child'=>array());
$result3 = $this->data->get_test('kdoutput','kdoutput','kdprogram = '.$row1['kdprogram'].' and kdgiat = '.$row2['kdgiat']);
foreach($result3 as $c_counter=>$row3)
{
$array_temp[$a_counter]['child'][$b_counter]['child'][$c_counter] = array( 'parent'=>$row3 , 'child'=>array());
$result4 = $this->data->get_test('kdsoutput','kdsoutput','kdprogram = '.$row1['kdprogram'].' and kdgiat = '.$row2['kdgiat'] .' and kdoutput = '.$row3['kdoutput']);
foreach($result4 as $row4)
{
$array_temp[$a_counter]['child'][$b_counter]['child'][$c_counter]['child'][] = $row;
}
}
}
}
in the view
foreach($result as $a )
{
// show a
foreach($a['child'] as $b )
{
// show b
foreach($b['child'] as $c )
{
// show c
foreach($c['child'] as $d )
{
// show d
}
}
}
}

counting session units from array PHP

I want to count my $_SESSION['cart'] (units) products from my basket.
#check added stock
$units = (int) $_POST['units'];
$sizes_id = (int) $_POST['size_id'];
$in_stock = $db->GetScalar("SELECT p.units FROM products_sizes s
INNER JOIN products p ON p.product_id = s.product_id
WHERE s.id = '$sizes_id' LIMIT 1");
$total = isset($_SESSION['cart'][$sizes_id]) ? $_SESSION['cart'][$sizes_id]['units'] : 0;
$total += $units;
if($total <= $in_stock) {
if(isset($_SESSION['cart'][$sizes_id])) {
$_SESSION['cart'][$sizes_id]['units'] = $total;
} else {
$_SESSION['cart'][$sizes_id] = array('size' => $sizes_id, 'units' => $total);
}
$msg = 'Added';
$status = 1;
}else {
$msg = 'Product is not in the basket';
$status = 0;
}
This is how the output looks like
Array(
[57] => Array
(
[size] => 57
[units] => 5
)
[56] => Array
(
[size] => 56
[units] => 1
)
)
Ok here goes
<?php
$total_units = 0;
foreach ($_SESSION['cart'] as $key => $value) {
$total_units += $value['units'];
}
echo $total_units;
?>
Should get the answer
This should do the job:
$numUnits = 0;
foreach ($yourArray as $item)
$numUnits += $item['units'];

Categories