I have 3 level nested array and I would like some help to make the generate the sum of its values.
The array goes like
SUM
/ \
A B
/ \ /\
Billed Route Billed Route
/ \ / \
Value Value Value Value
How can i make a sum of the Billed and Route fields?
So far I have this code
foreach($sum as $client)
{
$s = 0;
foreach($client as $stat_name=>$stat_value)
{
$val = 0;
// echo "<br><u><i>";
// echo $stat_name;
// echo "</u></i><br>";
foreach($stat_value as $value)
{
$val += intval($value);
}
$sum2[$stat_name] += $val;
}
}
I receive an undefine index error on the first loop for each new key.
Have you defined $sum2[$stat_name] as 0 ? If not, you'll get an undefined index error on each iteration of the second foreach loop because you're trying to do += on a value that isn't defined.
Also, if you're trying add the values of Billed and Route then storing them in different parts of an associative array ($sum2[$stat_name]) is an extra step. Just add them together in the same key of the array.
If those are the actual keys in your array, then:
$route = 0;
$billed = 0;
foreach($yourarray['SUM'] AS $ab => $subarray) {
$billed += $subarray['Billed']['Value'];
$route += $subarray['Routed']['Value'];
}
$sum2[$stat_name] += $val;
is the same as:
$sum2[$stat_name] = $sum2[$stat_name] + $val;
^^^^^^^^^^^^^^^^^ undefined the first time you loop
To solve that, you should initialize it:
$sum2[$stat_name] = isset($sum2[$stat_name]) ? $sum2[$stat_name] : 0;
$sum2[$stat_name] += $val;
Related
I am attempting to sum two arrays and subtract them from each other in PHP. Below is my attempt at it:
function total_price($totals)
{
$sum = 0;
$sub = 0;
foreach ($totals as $total)
{
$sum += $total['total_selling_price'];
$sub += $total['total_buying_price'];
$profit = $sum - $sub;
}
What I'm trying to do is sum up everything in the sales array and subtract it by everything in the costs array (represented by variable $sub) in order to generate profit. However, I'm unable to, and I get the following error:
UNDEFINED VARIABLE: PROFIT.
I've declared a profit variable within the foreach, so can someone tell me why my variable is considered undefined?
Assign $profit = 0 out of loop.
Also validate totals before iterating.
if(is_array($totals)){
foreach($totals as $total ){
// write your code here
}
}
i want to calculate two operations with the help of loop. They are already working and providing result i need. But i want them to look more like coding. So if anybody can help them with the help of for in php
for($i=0;i<something;$i++){
$temp_calc = ;
}
here are two statements.
In first statement length of array is 9.
In second statement length of array is 12.
both statements to be solved in different for loop as they are totally different questions.
$temp_calc = 10*$temp_array[0]+9*$temp_array[1]+8*$temp_array[2]+7*$temp_array[3]+6*$temp_array[4]+5*$temp_array[5]+4*$temp_array[6]+3*$temp_array[7]+2*$temp_array[8];
$temp_calc = 1*$temp_array[0]+3*$temp_array[1]+1*$temp_array[2]+3*$temp_array[3]+1*$temp_array[4]+3*$temp_array[5]+1*$temp_array[6]+3*$temp_array[7]+1*$temp_array[8]+3*$temp_array[9]+1*$temp_array[10]+3*$temp_array[11];
Thanks in advance
It will be a little simpler to use a foreach loop rather than a for loop. If you specifically need to use a for loop because it is a requirement of an assignment, you can check the PHP documentation. There are some examples there of using a for loop to loop over an array. This is a common and basic control structure and it will be more valuable for you to really understand how to use it. The more important part is what goes on inside the loop. There are multiple ways to do this, but here are some basic examples.
First one:
// initialize multiplier and result outside the loop
$multiplier = 10;
$result = 0;
// loop over the values
foreach ($temp_array as $value) {
// add the value * multiplier to the result and decrement the multiplier
$result += $value * $multiplier--;
}
Second one
// initialize multiplier and result outside the loop
$multiplier = 1;
$result = 0;
// loop over the values
foreach ($temp_array as $value) {
// add the value * multiplier to the result
$result += $value * $multiplier;
// switch the multiplier to the alternating value
if ($multiplier == 1) {
$multiplier = 3;
} else {
$multiplier = 1;
}
// The switch can be done more simply using a ternary operator like this:
// $multiplier = $multiplier == 1 ? 3 : 1;
}
for both issues:
$temp_array = array(2,2,2,2,2,2,2,2,2);//sample
function calc_1($temp_array){//first
$total=0;
$count = count($temp_array)+1;
foreach($temp_array as $value){
$total += $count*$value;
$count-=1;
}
return $total;
}
function calc_2($temp_array){//second
$total=0;
foreach($temp_array as $k=>$value){
$total += ($k%2==0) ? 1*$value : 3*$value;//when is even or odd
}
return $total;
}
var_dump(calc_1($temp_array));//resp1
var_dump(calc_2($temp_array));//resp2
If your array is called $myArray, then:
/*Since I can't know what the sequence of the values are that you
are multiplying, and because you might need other sequences in the
future, a function was developed that chooses which sequence you
want to multiply.*/
function findSomeValues($arraySize)
{
switch ($arraySize) {
case 9:
{
$someValues = array(10,9,8,7,4,5,4,3,2);
}
break;
case 12:
{
$someValues = array(1,3,1,3,1,3,1,3,1,3,1,3);
}
break;
default:
$someValues = array();
}
return $someValues;
}
/*This following function then finds how big your array is, looks
for a sequence stored in the findSomeValues function. If a sequence
exist for that array size (in this case if you have an array either
9 or 12 elements long), the result will be calculated and echoed. If
the sequence was not found, an error message would be echoed.*/
function multiplyValues($myArray) {
$result = 0;
$arraySize = count($myArray);//obtaining array size
$someValues = findSomeValues($arraySize);//obtaining sequence to multiply with
if (count($someValues)>0)
{
for($i=0;i<$arraySize;$i++){
$result += $myArray[i]*$someValues[i];
}
echo "result = ".$result."<br>";//result message
}
else
{
echo "you are missing some values<br>";//error message
}
}
Let me know if that worked for you.
Alternative:
If you prefer something a bit simpler:
//this array holds the sequences you have saved:
$sequenceArray = array(
9 => array(10,9,8,7,4,5,4,3,2),
12 => array(1,3,1,3,1,3,1,3,1,3,1,3)
);
//this function does the multiplication:
function multiplyValues($myArray)
{
$arraySize = count($myArray);
for($i=0;i<$arraySize;$i++){
$result += $myArray[i]*$sequenceArray[i];
}
echo "result = ".$result."<br>";//result message
}
For your result
$temp_calc = 10*$temp_array[0]+9*$temp_array[1]+8*$temp_array[2]+7*$temp_array[3]+6*$temp_array[4]+5*$temp_array[5]+4*$temp_array[6]+3*$temp_array[7]+2*$temp_array[8];
You should have for loop as following. It will run the loop till 8th index of your temp_array and multiply each index value with $i and sum up in a variable $temp_calc_1.
<?php
$temp_calc_1 = 0;
for($i=0;$i<9;$i++){
$temp_calc_1 = $temp_calc_1 + ( 10-$i)*$temp_array[$i] ;
}
For your second result
$temp_calc = 1*$temp_array[0]+3*$temp_array[1]+1*$temp_array[2]+3*$temp_array[3]+1*$temp_array[4]+3*$temp_array[5]+1*$temp_array[6]+3*$temp_array[7]+1*$temp_array[8]+3*$temp_array[9]+1*$temp_array[10]+3*$temp_array[11];
The above should be converted to the following loop, this will run loop till your 12th index of temparrayand do the calculation. This time it will multiply each index value of temparray by either 1 and 3. So first time it will multiply with 1 and next time with 3 and so on
//
$temp_calc_2 = 0;
for($i=0;$i<12;$i++){
$j = $i%2?3:1;
$temp_calc_2 = $temp_calc_2 + $j*$temp_array[$i] ;
}
?>
I asked a similar question earlier but I couldn't get a clear answer to my issue. I have a function "isParent" that gets 2 pieces of data. Each 1 of the 2 gets a string separating each value with a , or it just gets a plain int and then checks if the first value given is a parent of the second.
I pull the 2 bits of data in and explode them but when I go through my nested for loop and try to test
$toss = $arr1[$i];
print_r($toss);
It comes up blank. I have no idea what the issue is: Here is the full code of the function...
function isParent($parent, $child)
{
$parentArr = explode(',', $parent);
$childArr = explode(',',$child);
//Explode by Comma here. If array length of EITHER parentArr or childArr > 1 Then throw to an Else
if(count($parentArr) <= 1 && count($childArr) <= 1) //If explode of either is > 1 then ELSE
{
$loop = get_highest_slot(15);
for($i = $loop; $i > 0; $i--)
{
$temp = get_membership_from_slot($i,'id_parent','id_child');
if($temp['id_parent'] == $parent && $temp['id_child'] == $child)
{
return 1;
}
}
}
else //set up a for loop in here so that you traverse each parentArr value and for each iteration check all child values
{
$i = count($parentArr);
$c = count($childArr);
for(;$i >=0;$i--) //Loop through every parent
{
for(;$c >=0;$c--)
{
echo '<br>$i = ';
print_r($i);
echo '<br><br>Parent Arr at $i:';
$toss = $parentArr[$i];
echo $toss;
echo '<br>';
print_r($childArr);
echo '<br><br>';
if(isParent($parentArr[$i],$childArr[$c])) //THIS CAUSES AN INFINITE YES! Learn how to pull an array from slot
{
return 1;
}
}
}
}
return 0;
}
You are missing some code for the slot procedures. Apart from that, you probably need to use a different variable for the inner for loop. because $c will be 0 after the first iteration of $i.
Thanks for the help! The issue was in the recursive call back to the top of the function. It was tossed empty slots and when comparing 2 empty slots it returned a false positive. A quick !empty() check fixed it.
I've seen questions like this, but if I assign a key-value pair to an empty array lik this
$arr[$key] = $value;
I get the php notice
Notice: Undefined index: <key> in <path>
where of course <key> is whatever value was in $key.
How can I assign a value to a new key, without triggering a Notice?
Thanks!
edit: heres your more precise code. This is exactly whats in my code. Does this any difference?
while( list( $k, $sum ) = mysql_fetch_row( $res ) ) {
if( $sum < 0 ) {
$churn[$k] += $sum;
}
}
declare your array before addind the key
$arr = array();
$arr[$key] = $value;
or simply do
$arr = array($key=>$value);
what do you mean [$value]
You're trying to get the value of a brand new array with a given key
Your syntax isnt correct. Just try my quick testcase which wont throw any notice.
<?php
error_reporting(E_ALL);
$array = array();
$key = 'new_key';
$value = 'new_value';
$array[$key] = $value;
echo '<pre>';
var_dump($array);
exit;
?>
The problem layed in
while( list( $k, $sum ) = mysql_fetch_row( $res ) ) {
if( $sum < 0 ) {
$churn[$k] += $sum;
}
}
due to the += operator. The first time, it gets called, churn['whateverWasIn$k'] is not set. The second time is fine though.. So to get rid of the notices, it has to be like:
(!isset($churn[$k])) ? $churn[$k] = $sum : $churn[$k] += $sum;
Realize the missing + in the middle statement. So if this key does not exist by the time, i want to increase it by $sum, declare it and give it the value of $sum, otherwise just add $sum to the current value.
That's all. It doesn't look to pretty in code, but it gets me rid of 200 notices. Which also doesn't look too nice in my view.
Thanks for your help.
Hopefully this is a simple answer or doable in some other way. I want to use parse_str to store my querystring values in an array.
$querystring = "value1=SKIP&value2=SKIP&value3=GET&value4=GET";
parse_str($querystring, $fields);
Accessing the data by name works correctly:
echo $fields['value3'];
... but accessing via index does not:
echo $fields[2];
The reason I want to access by index instead of name is because after the 2nd array value, the rest of the querystring parameters will be DYNAMICALLY generated. In other words, for the processing I'm doing -- I want to get all parameters AFTER the 2nd one. To do that, I was going to use a simple FOR loop starting from the 3rd value in the array to the sizeof(myArray);.
Any ideas how I can accomplish this?
You have to generate an indexed array then. You could for example use:
$indexed = array_values($fields);
print $indexed[2]; // eqivalent to $fields["value3"];
Note that the index starts from 0.
If you want you could also combine the named array with the indexed version:
$fields = array_merge($fields, array_values($fields));
$fields[2] == $fields["value3"];
$i = 0;
foreach ($fields as $key => $value) {
$fields[$i] = $value; //or just put your code here, and use $i
$i++;
}
for ($j = 2; $j < $i; $j++) {
//do something with $fields[$j]
}
Here:
$querystring = "value1=SKIP&value2=SKIP&value3=GET&value4=GET";
parse_str($querystring, $fields);
$arr = array_slice($fields, 2, count($fields), true);
foreach($arr as $key=>$value) {
echo $key . "=>" . $value;
}
Just concatenate a string with an integer:
echo $fields["value" . $myInteger + 1];
where myInteger is your value (for loop, etc.). You need to add 1 because your strings are one-based.
Example:
for ($i = 2; $i < sizeof($myArray); $i++)
{
echo $fields["value" . $i + 1];
}