Add value of columns in foreach loop. - php

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.

Related

Consolidate array of numbers without exceeding a predefined maximum value per element

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.

How to add the values from a foreach loop php

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.

Get x highest values from an array including identical values

I'm using the following code to retrieve the highest 3 numbers from an array.
$a = array(1,2,5,10,15,20,10,15);
arsort($a, SORT_NUMERIC);
$highest = array_slice($a, 0, 3);
This code correctly gives me the highest three numbers array(20,15,10); however, I'm interested in getting the highest 3 numbers including the ones that are identical. In this example, I'm expecting to get an array like array(10, 10, 15, 15, 20)
Might be simpler but my brain is tired. Use arsort() to get the highest first, count the values to get unique keys with their count and slice the first 3 (make sure to pass true to preserve keys):
arsort($a, SORT_NUMERIC);
$counts = array_slice(array_count_values($a), 0, 3, true);
Then loop those 3 and fill an array with the number value the number of times it was counted and merge with the previous result:
$highest = array();
foreach($counts as $value => $count) {
$highest = array_merge($highest, array_fill(0, $count, $value));
}
You can use a function like this:
$a = array(1,2,5,10,15,20,10,15); //-- Original Array
function get3highest($a){
$h = array(); //-- highest
if(count($a) >= 3){ //-- Checking length
$c = 0; //-- Counter
while ($c < 3 || in_array($a[count($a)-1],$h) ){ //-- 3 elements or repeated value
$max = array_pop($a);
if(!in_array($max,$h)){
++$c;
}
$h[] = $max;
}
sort($h); //-- sorting
}
return $h; //-- values
}
print_r(get3Highest($a));
Of course you can improve this function to accept a dinamic value of "highest" values.
The below function may be usefull
$a = array(1,2,5,10,15,20,10,15);
function getMaxValue($array,$n){
$max_array = array(); // array to store all the max values
for($i=0;$i<$n;$i++){ // loop to get number of highest values
$keys = array_keys($array,max($array)); // get keys
if(is_array($keys)){ // if keys is array
foreach($keys as $v){ // loop array
$max_array[]=$array[$v]; // set values to max_array
unset($array[$v]); // unset the keys to get next max value
}
}else{ // if not array
$max_array[]=$array[$keys]; // set values to max_array
unset($array[$keys]); // unset the keys to get next max value
}
}
return $max_array;
}
$g = getMaxValue($a,3);
Out Put:
Array
(
[0] => 20
[1] => 15
[2] => 15
[3] => 10
[4] => 10
)
You can modify it to add conditions.
I thought of a couple of other possibilities.
First one:
Find the lowest of the top three values
$min = array_slice(array_unique($a, SORT_NUMERIC), -3)[0];
Filter out any lower values
$top3 = array_filter($a, function($x) use ($min) { return $x >= $min; });
Sort the result
sort($top3);
Advantages: less code
Disadvantages: less inefficient (sorts, iterates the entire array, sorts the result)
Second one:
Sort the array in reverse order
rsort($a);
Iterate the array, appending items to your result array until you've appended three distinct items.
$n = 0;
$prev = null;
$top = [];
foreach ($a as $x) {
if ($x != $prev) $n++;
if ($n > 3) break;
$top[] = $x;
$prev = $x;
}
Advantages: more efficient (sorts only once, iterates only as much as necessary)
Disadvantages: more code
This gives the results in descending order. You can optionally use array_unshift($top, $x) instead of $top[] = $x; to get it in ascending order, but I think I've read that array_unshift is less efficient because it reindexes the array after each addition, so if optimization is important it would probably be better to just use $top[] = $x; and then iterate the result in reverse order.

Multiply value of 2 indexes in foreach loop

I want to multiply the values of 2 indexes in my foreach loop.
E.G.
foreach($items as $item)
{
$result=$item['foo']*$item['bar'];
}
Then I want to return the result of the sum of all the $result within the function. For example,there are 2 rows of results in the foreach loop, I want to sum them up and return $sum. Anybody knows how to do that?
$sum = 0;
foreach($items as $item)
{
$result=$item['foo']*$item['bar'];
$sum += $result;
}
return $sum;
Is this what you want. It will add all $result in $sum and return $sum if this code is in a function.

How to do PHP matrix operation easily and gracefully?

I've a $max which is essentially a two dimensional array.
Each element in $max is eithor 1 or 0,
can be denoted by $max[$x][$y], where $x is an integer within 0~WIDTH,similar for $y
My purpose is to find rows and columns in the $maxthat sums up greater than a CONSTANT, and get the average distance between rows/columns that qualify.
Anyone has a good solution ?
I have not tested this, but it should work for summing up the columns and rows:
//Map columns and rows into their respective values
//Note that we preserve the col/row indexes
$rowval = array();
$colval = array();
foreach($max as $k1 => $row) {
$rowval[$k1] = array_sum($row);
foreach($row as $k2 => $col) {
if(!isset($colval[$k2])) {
$colval[$k2] = 0;
}
$colval[$k2] += $col;
}
}
//Define filter function
function is_over($val) {
return $val > CONSTANT;
}
//Filter out the cols/rows from their respective arrays
//Keys will be preserved by array_filter
$foundcols = array_filter($colval, 'is_over');
$foundrows = array_filter($rowval, 'is_over');
You still have to calculate the average distance though.

Categories