I have and foreach loop that outputs the totals I want to add when i echo the $val_tex it outputs in one number like "4911165" but if I echo it with a break tag it gives me the right values. It looks like
49
1
1
1
65
My question is how to get the sum of all the values which should equal "117"
$val_tex = array();
foreach ( $get_seller as $keys ) {
$val_tex = $keys['total'];
}
You have to add them together in the foreach loop - there's a simple way to do that $total += $keys['total']; It's just a simpler way of saying $total = $total + $keys['total'];
There are also other ways - $total = array_sum(array(1,2,3,4)); // == 10 for example. To get the sum from a single column, you get an array that only contains the values from the specific column first:
// an array of the values from that column
$arrayTotall = array_column($keys, 'total');
$total = array_sum($arrayTotals);
Your for each needs another variable to add them:
foreach ( $get_seller as $keys ) {
$val_tex = $keys['total'];
$sum = += $val_tex
//or...
$val_tex += $keys['total'];
//depending on how you want to us val_tex
}
The .= adds the value to previous value instead of overwriting it.
Related
I'm trying to combine numbers in an array by adding them so that the max value can only by 30.
For example, this is my array:
array(10,30,10,10,15);
After combining the numbers in the array to items with a max value 30, the result should be:
array(30,30,15);
How to achieve this?
I'm trying to combine numbers in an array by adding them so that the
max value can only by 30
So, when you combine numbers, you can achieve the lowest possible set of values in your array and also make sure that max value remains 30 by:
First, sort them.
Second, keeping adding elements to sum till you are about to get a sum > 30.
Third, once an element can no longer be added to a sum, add the current sum in your array and make the current element as the new sum.
Code:
<?php
$arr = array(10,30,10,10,15);
sort($arr);
$res = [];
$curr_sum = 0;
foreach($arr as $each_value){
if($curr_sum + $each_value <= 30) $curr_sum += $each_value;
else{
$res[] = $curr_sum;
$curr_sum = $each_value;
}
}
$res[] = $curr_sum;
print_r($res);
Demo: https://3v4l.org/BYhuE
Update: If order of the numbers matters, seeing your current output, you could just use rsort() to show them in descending order.
rsort($res);
$total = array_sum(array(10,30,10,10,15)); //assign sum totals from orignal array
$maxValue = 30; //assign max value allowed in array
$numberOfWholeOccurancesOfMaxValue = floor($total/$maxValue);
$remainder = $total%$maxValue;
//build array
$i=0;
while ( $i < $numberOfWholeOccurancesOfMaxValue ){
$array[] = $maxValue;
$i++;
}
$array[] = $remainder;
print_r($array);
You can loop only once to get this,
$temp = array(10,30,10,10,15);
natsort($temp); // sorting to reduce hustle and complication
$result = [];
$i = 0;
$maxValue = 30;
foreach($temp as $v){
// checking sum is greater or value is greater or $v is greater than equal to
if(!empty($result[$i]) && (($result[$i]+$v) > $maxValue)){
$i++;
}
$result[$i] = (!empty($result[$i]) ? ($result[$i]+$v) : $v);
}
print_r($result);
Working demo.
I believe finding most space-optimized/compact result requires a nested loop. My advice resembles the firstFitDecreasing() function in this answer of mine except in this case the nested loops are accessing the same array. I've added a couple of simple conditions to prevent needless iterations.
rsort($array);
foreach ($array as $k1 => &$v1) {
if ($v1 >= $limit) {
continue;
}
foreach ($array as $k2 => $v2) {
if ($k1 !== $k2 && $v1 + $v2 <= $limit) {
$v1 += $v2;
unset($array[$k2]);
if ($v1 === $limit) {
continue 2;
}
}
}
}
rsort($array);
var_export($array);
By putting larger numbers before smaller numbers before processing AND by attempting to add multiple subsequent values to earlier values, having fewer total elements in the result is possible.
See my comparative demonstration.
I believe #Clint's answer is misinterpreting the task and is damaging the data by summing all values then distributing the max amounts in the result array.
With more challenging input data like $array = [10,30,5,10,5,13,14,15,10,5]; and $limit = 30;, my solution provides a more dense result versus #nice_dev's and #rahul's answers.
I get the error Undefined index: item_total on the line $totals['item_total'] += (float)$quantity; I want $totals array to contain the $mycart summarized quantity data by Product.
$mycart = array();
$mycart[0]['product'] = 'ProductA';
$mycart[0]['quantity'] = 10;
$mycart[1]['product'] = 'ProductA';
$mycart[1]['quantity'] = 4;
$mycart[2]['product'] = 'ProductB';
$mycart[2]['quantity'] = 8;
$mycart[3]['product'] = 'ProductB';
$mycart[3]['quantity'] = 8;
$totals = array();
foreach ($mycart as $row)
{
$product = $row['product'];
$quantity = $row['quantity'];
$totals['item_total'] += (float)$quantity;
}
In php you can create an array index by $totals['item_total'] = value;. And you cannot use an array index in an expression if it has not been "initialized". What do you see when you write this statement out $totals['item_total'] += (float)$quantity; "long hand"? It is just a shortcut for $totals['item_total'] = $totals['item_total'] + (float)$quantity;. In the right-hand expression $totals['item_total'] has not been initialized, thus program gives "Undefined index" message.
Your problem comes from using increment with an undefined variable
$totals['item_total'] += (float)$quantity;
The reason for this is that increment does a read (to get the current value) of the variable, before increment it. Which makes sense because we need to know it's current value before we can add 1 to it.
Now because that variable is not defined, you get an error message Undefined index: item_total". Which also makes sense because we cannot get the value of something (read it) that has not been defined, because it doesn't exist yet.
To further illustrate this, we can manually increment without the += like this:
$totals['item_total'] = $totals['item_total'] + 1;
We should agree this is the same as $totals['item_total'] += 1 as they give the same value, but here you can see how we must reference the previous value of that variable, which is the same thing that += must do. And in the same line of reason we cannot read it if it's not defined.
#Psudo for $var = $var + 1
write = read + 1
When simply assigning like this:
$totals['item_total'] = 0;
There is no reading (of an undefined value, as we know what 0 is) that takes place, so PHP is fine with that variable not existing and just creates it. Some languages are not that forgiving. What I mean here is some languagues you would need to first define $totals as an array, and then add stuff to it. In PHP $totals doesn't even need to exist to do $totals['item_total'] = 0;
So as others noted you need to define it with a value of 0 before hand, that way when the read is done it will know it's 0 and you wont see the error.
$totals['item_total'] = 0;
//or $totals = ['item_total' => 0];
foreach ($mycart as $row)
{
$product = $row['product'];
$quantity = $row['quantity'];
$totals['item_total'] += (float)$quantity;
}
echo $totals['item_total'];
Output
30
Sandbox
PHP is actually very forgiving about undefined variables, but in cases where it must first read that variable, it must be defined beforehand.
UPDATE
Based on this comment
I want it summed by product -- ProductA = 14 and ProductB = 16.
You can do it this way:
$mycart = array();
$mycart[0]['product'] = 'ProductA';
$mycart[0]['quantity'] = 10;
$mycart[1]['product'] = 'ProductA';
$mycart[1]['quantity'] = 4;
$mycart[2]['product'] = 'ProductB';
$mycart[2]['quantity'] = 8;
$mycart[3]['product'] = 'ProductB';
$mycart[3]['quantity'] = 8;
$totals = array();
foreach ($mycart as $row)
{
$key = $row['product'];
if(!isset($totals[$key])){
$totals[$key] = $row;
// $totals[$key] = $row['quantity']; //just [key=>quantity] no inner array
}else{
$totals[$key]['quantity'] += $row['quantity'];
// $totals[$key] += $row['quantity']; //just [key=>quantity] no inner array
}
}
print_r($totals);
Output
Array
(
[ProductA] => Array
(
[product] => ProductA
[quantity] => 14
)
[ProductB] => Array
(
[product] => ProductB
[quantity] => 16
)
)
/*
without the inner array
Array
(
[ProductA] => 14
[ProductB] => 16
)
*/
Sandbox
See my comments in the code on how to remove the inside array if you want just the Key and it's total quantity. If you do want the inner arrays but not the top level key (product), you can do this to remove those.
//after the loop
$totals = array_values($totals); //resets array keys to numbered keys
This will replace the ProductA and ProductB keys with 0 and 1.
Enjoy.
Simply add this line right before foreach:
$totals['item_total']=0;
I want all rating values sum then divided with 5
array (size=2)
0 =>
object(stdClass)[571]
public 'rating' => string '3' (length=1)
1 =>
object(stdClass)[300]
public 'rating' => string '5' (length=1)
You can either use a 'foreach' block, iterate over each element in your array and sum up its 'rating' value
foreach($array->items as $item) {
$sum+=(int)$item->rating;
}
$result = $sum/5;
Or you can use the array_sum() method
$sum =array_sum((int)$array->rating);
$result = $sum/5;
PHP 7 solution:
$result = array_sum(array_column($array_of_objects, 'rating')) / 5;
you can use this code for sum array value using php . First assign variable shich store all sum value so this must set 0 and use loop for make all value sum. this is your code which help you and if your array $your_array then
$sum = 0; // this is store all sum value so first assign 0
foreach ($your_array as $rating) {
{
$sum += $rating->rating; // sum value with previous value and store it and no need to convert string type to int cause php do it
}
echo $sum; // this is final value
echo $total_sum = $sum / 5; // this is your desire result
and if your array is associative then use this code
$sum = 0; // this is store all sum value so first assign 0
foreach ($your_array as $rating) {
{
$sum += $rating['rating']; // sum value with previous value and store it and no need to convert string type to int cause php do it
}
echo $sum; // this is final value
echo $total_sum = $sum / 5; // this is your desire result
check this code and hope it will help you .
$sum = 0;
foreach($array as $val){
$sum += (int) $val->rating;
}
// divide by 5
$average = $sum/5;
for average, I think you should divide sum by no. of result like
$average = $sum/count($array);
I have quantity in two diff tables . i want to add those quantities and update it into table3 amount column.
I have wrote this code but the value is showing 0
foreach($products as $key =>$value)
{
echo $totalquantity = $value->amount+ $value->QuantityAvailable;
$updtqry="UPDATE stock SET amount = $totalquantity where id_stock='".$value->id_stock."'";
mysql_query($updtqry);
}
I just want to know how to get a sum of array values within foreach loop
Well you get sum of two arrays containing numeric values like this:
$sum = 0;
foreach($amountArray as $amount) {
$sum += $amount;
}
foreach($amountArray2 as $amount) {
$sum += amount;
}
// update with $sum...
1.) If you want to find the sum of the elements of one particular array. You could use array_sum().
array_sum($array1);
2.) If you want to get the sum of two array you could do it the following way, provided the arrays are numerically indexed.
for($index=0; $index < count($array1); $index++) {
$array3[$index] = $array1[$index] + $array2[$index];
}
Here $array1 and $array2 are the values of which are to be added and stored in $array3.
3.) If the arrays are not numerically indexed then you could do this:
for ($counter=0;$counter<count($array1);$counter++) {
$array3[$counter] = current($array1) + current($array2);
next($array1); next($array2);
}
The number of the elements of the two arrays should be equal for it to work.
For example I have a mysql_num_rows results of 4,8,15,16,23,42 in a query that is inside a while loop of another query. My question is how can I get the percentage per each result of mysql_num_rows inside my while loop? Example: 4,8,15,16,23,42. Total is 108. $sum = 108. Percentage of 4 = 4/$sum = 3.7%, 8 = 8/$sum = 7.4% and so on..
you can store all the values in an array and do the calcs after you have retrieved the data from the database
eg
$datastore = array();
$total = 0;
while(list($amount) = mysql_fetch_row($result)) {
$datastore[] = $amount;
$total += $amount;
}
foreach ($datastore as $amount) {
echo $amount," - ";
printf("%5.2f", $amount/$total);
echo "\r\n";
}
$values = array(4, 8, 15, ...);
$sum = array_sum($values);
foreach($values as $value) {
echo ($value / $sum) * 100;
}
CodePad.
So you are saying that you want the $sum before the individual results right? You could do a simple additional query to get the sum before you pull out the individual results. Use the SUM aggregate function. It is probably also possible to get the percentage in your SQL results. That would mean a slightly more complex query, but not an additional query.