I wrote this code to sum only amount but is not working.Everything works perfectly except the sum. Can some one help me out?
Here is the code:
<tr >
<td > Total </td>
<td >
<?php $sum2=0; foreach($contributions_ as $val){
$sum = $sum2 + $contributions_[$val];
}echo array_sum($contributions_);
?>
</td>
</tr>
Here is the php:
<?php
$tempArray = array(
$rowRes['amount'],
$rowRes['remarks'],
$rowRes['ID']
);
$contributions_[] = $tempArray;
?>
I want to sum only amount(s) whiles the condition is true
This is my query which worked perfectly but cannot sum amount after displaying the various members contributions .
<?php $selectQuery = "select a.*,b.* ID, monthname(date) as month,month(date) as mnth, year(date) as yr, type,amount, recipient_initials,remarks, in_kind_items,other_type,other_payment_name,date from member_payments a inner join member b on a.memberID = b.ID";
?>
Why can't I sum amount here like SUM(amount)
<tr >
<td> Total </td>
<td>
<?php
$sum = 0;
foreach($contributions_ as $val){
$sum = $sum + $val['amount'];
}
echo $sum;
?>
</td>
</tr>
<?php
$tempArray = array(
$rowRes['amount'],
$rowRes['remarks'],
$rowRes['ID']
);
$contributions_[] = $tempArray;
$sum += $rowRes['amount'];
?>
Got it now after echoing sum
You used $sum and $sum2 in this line:
$sum = $sum2 + $contributions_[$val];
If I'm reading your code right, it should be more like this:
<?php $sum2=0; foreach($contributions_ as $val){
$sum2 = $sum2 + $contributions_[$val];
}echo $sum2;
?>
Sorry, I don't know what you mean by "I want to sum only amount(s) whiles the condition is true".
Related
Data:
MEL1INFA73 Confirmed. Ksh29.00 sent to Safaricom Offers for account Tunukiwa on 21/5/18 at 3:29 AM New M-PESA balance is Ksh5.50. Transaction cost, Ksh0.00.
MEE6ESSVCS Confirmed. Ksh2,240.00 paid to Naivas West End Plaza. on 14/5/18 at 8:13 PM.New M-PESA balance is Ksh4,753.50. Transaction cost, Ksh0.00.
MEF1EZ0MNR Confirmed.You have received Ksh10,000.00 from Barclays Bank K LTD 303031 on 15/5/18 at 9:36 AM New M-PESA balance is Ksh14,775.50. Buy goods with M-PESA.
The following code generates sum of figures in each row other than the whole column:
<?php
if(count($json_data["data"]) > 0){ ?>
<?php $_count = 1;
foreach($json_data["data"] as $row){ ?>
<tr>
<td><?php
$str =$row["msg_body"];
preg_match_all("/ksh\s*(\d+\.\d+)/i", $str, $matches);
echo array_sum($matches[1]); ?></td>
</tr>
<?php $_count ++; }
?>
<?php }else{
}
?></td>
If I understand correctly you just need to store the whole sum and then print it out somewhere. Something like:
<?php
if(count($json_data["data"]) > 0){ ?>
<?php $_count = 1;
$totalSum = 0;
foreach($json_data["data"] as $row) { ?>
<tr>
<td><?php
$str =$row["msg_body"];
preg_match_all("/ksh\s*(\d+\.\d+)/i", $str, $matches);
$rowSum = array_sum($matches[1]);
$totalSum += $rowSum;
echo $rowSum;?></td>
</tr>
<?php $_count ++; }
?>
<tr><td>Total sum: <?php echo $totalSum; ?></td></tr>
<?php }else{
}
?></td>
You can adjust your html, of course.
Because we are dealing with an array and preg_match_all, then I believe you could implode the array and do one preg_match_all instead of looping it.
$AllItems = implode(" ", $json_data["data"]);
preg_match_all("/ksh\s*(\d+\.\d+)/i", str_replace(",","",$AllItems), $matches);
$total = array_sum($matches[1]);
Example:
https://3v4l.org/Pk7YT
Edit noticed there was commas as thousands separators. That needs to be removed for the regex and summing to work with str_replace.
<?php
$new_result = mysqli_query($con, "SELECT input_cost FROM data_input");
while ($new = mysqli_fetch_array($new_result)) {
$sum += $new['input_cost'];
}
echo "<h2> total cost of this month is $".$sum. "</h2>";
?>
but the result say
<br>
Notice: Undefined variable: sum in
C:\xampp\htdocs\work_shop\back_end\data_input_output\result.php on
line 57
<br>
total cost of this month is $300
which is correct result....
<br>
How can I solve this problem...??
You need to define $sum variable outside loop. Try this-
<?php
$sum = 0; // define sum outside loop
$new_result = mysqli_query($con, "SELECT input_cost FROM data_input");
while ($new = mysqli_fetch_array($new_result)) {
$sum += $new['input_cost'];
}
echo "<h2> total cost of this month is $".$sum. "</h2>";
?>
$sum is undefined because you are only adding, and not setting a value.
<?php
$new_result = mysqli_query($con, "SELECT input_cost FROM data_input");
$sum = 0;
while ($new = mysqli_fetch_array($new_result)) {
$sum += $new['input_cost'];
}
echo '<h2> total cost of this month is $'.$sum.'</h2>';
?>
I have created a script that populates fields of a table dynamically using php. If you look at the snippet of code below, I have hit a brick wall now that I want to add all $sub_total to create a $total_cost. Not sure if I am explaining this well but any direction would be much appreciated.
// loop through results of database query, displaying them in the table
while($row = mysql_fetch_array( $result )) {
// Calculate hours done per day
$hrs_done = $row['time_out'] - $row['time_in'];
if($hrs_done > $row['con_hr']){$hrs = $hrs_done;}
else{$hrs = $hrs_done;}
// echo out results into a table
echo "<tr>";
echo '<td bgcolor="#FFFFFF">' . $row['date'] . '</td>';
echo '<td bgcolor="#FFFFFF">' . $hrs . '</td>';
echo '<td bgcolor="#FFFFFF">' . $row['rate'] . '</td>';
echo '<td bgcolor="#FFFFFF">'?>
// Multiply hrs by rate to get sub total charge for day
<?php $sub_total = $hrs * $row['rate'];
echo $sub_total ;
?>
<?php '</td>';
echo "</tr>";
}
// close table>
echo "</table>";
First, you should look for tutorials that use mysqli or PDO for database access, as mysql_* functions are deprecated.
Second this problem is as easy as just adding up the subtotal items as you iterate through the loop
$grand_total = 0;
while($row = mysql_fetch_array( $result )) {
// your other code omitted for clarity
$sub_total = $hrs * $row['rate'];
$grand_total += $sub_total;
echo $sub_total ;
// more code
}
echo $grand_total;
If I understand your desired behaviour correctly.
During the loop add each $sub_total to $total_cost and echo this after you've completed the while loop
<?php
$total_cost = 0;
while($row = mysql_fetch_array( $result )) {
$sub_total = $hrs * $row['rate'];
$total_cost += $sub_total;
}
echo "Total cost: " . $total_cost;
?>
Your IF/ELSE block leads to one and the same result in both conditions. Is that the desired result?
On the other hand, I'm not sure, if I understood you correct, but if I did, here's my answer.
Since you want to recieve all the $sub_total, you need all the other vars which have built $sub_total:
They are:
$hrs = $hrs_done = $row['time_out'] - $row['time_in']
$row['rate'];
If you try with the SUM() MySQL function, you will recieve the sum of the mentioned columns:
SELECT sum(time_out) as 'sum_time_out', sum(time_in) as 'sum_time_in', sum(rate) as 'sum_rate' FROM myTable;
$hrs_sum = $hrs_done_sum = $row['sum_time_out'] - $row['sum_time_in'];
$stotal_cost = $hrs)sum * $row['sum_rate'];
Each iteration of the while loop creates a new variable $subtotal that you want to add to your constant variable $total.
so within the loop you can add $subtotal to $total and echo the $total after the while loop exits
while($row = mysql_fetch_array( $result ))
{
// your code
$total = $total + $subtotal; // shorthand is - $total += $subtotal.
}
echo $total;
I use the following to print a 15-row, two-column table from an associative arrray in PHP:
<table id="freq-table" class="table-list" cellspacing="0" cellpadding="10">
<tbody>
<?
$rowCount = 0;
foreach($word_frequency as $word => $frequency) if ($rowCount++ < 15) {?>
<tr>
<td><? echo $word; ?></td>
<td<? echo $frequency; ?></td>
</tr>
<?}?>
</tbody>
</table>
It works fine but takes up too much vertical space on the page. How can I format this into three side-by-side tables of five rows and two columns each with the first group having array items 1-5, the second group 6-10, and the last group 11-15? (refer to following illustration):
key1 value1 | key6 value6 | key11 value11
key2 value2 | key7 value7 | key12 value12
...
...
key5 value5 | key10 value10 | key15 value15
I've tried various table, div, container, and multiple loop experiments with very mixed (and unsuitable) results. Thank you in advance.
Since you can also use multiple columns to achieve this visual effect, you're going to probably want to format the data ahead of time to make the code of generating the table a little cleaner.
<?php
// Format the array data so each row contains all of the columns needed
$rows = array();
$max_per_column = 5;
$max_words = 15;
$rows = array_pad($rows, $max_per_column, array());
$count = 0;
foreach ($word_frequency as $word => $frequency) {
if ($count >= $max_words) {
break;
}
array_push($rows[$count % $max_per_column], $word, $frequency);
$count++;
}
?>
<table id="freq-table" class="table-list" cellspacing="0" cellpadding="10">
<tbody>
<?php
foreach ($rows as $cols) {
echo '<tr><td>' . implode('</td><td>', $cols) . '</td></tr>';
}
?>
</tbody>
</table>
Try some thing like that.
<table width="100%">
<tr>
<?php
$rowCount = 0;
foreach($word_frequency as $word => $frequency) if ($rowCount < 15) { ?>
<?php if($rowCount % 5 == 0) { ?>
<td><table border=1>
<?php } ?>
<tr>
<td><?php echo $word; ?></td>
<td><?php echo $frequency; ?></td>
</tr>
<?php if($rowCount % 5 == 4) { ?>
</table></td>
<?php } ?>
<?php $rowCount++; } ?>
</tr>
</table>
The only way to do this is to use a numeric key. For example
$word_frequency[0] = array();
$word_frequency[0]['word'] = "some word";
$word_frequency[0]['frequency'] = 10;
...
$word_frequency[15] = array();
$word_frequency[15]['word'] = "some other word";
$word_frequency[15]['frequency'] = 14;
Once you have your array, you could repeat the loop as follows
<table id="freq-table" class="table-list" cellspacing="0" cellpadding="10">
<tbody>
<?
$rowCount = 0;
for($i = 0; $i <= 5; $i++) {
$word[0] = $word_frequency[$i]["word"];
$frequency[0] = $word_frequency[$i]["frequency"];
$word[1] = $word_frequency[$i + 5]["word"];
$frequency[1] = $word_frequency[$i + 5]["frequency"];
$word[2] = $word_frequency[$i + 10]["word"];
$frequency[2] = $word_frequency[$i + 10]["frequency"];
?>
<tr>
<?
for($x = 0; $x <= 2; $x++ ){
?>
<td><? echo $word[$x]; ?></td>
<td<? echo $frequency[$x]; ?></td>
<?
}
?>
</tr>
<?
}
?>
</tbody>
</table>
Every $i loop creates the row, while the $x loop creates the columns. This assumes, of course, that you have at least 15 items, that you're going to create only 5 rows and three columns of key/value pairs.
Well, if I were doing it, I'd probably use a ul with a css columns :D
http://davidwalsh.name/css-columns
However, that's not a very "programmerly" thing to do.
It might help that you don't have to go through the array in order.
If you look at what you have, there is a pattern to the indices:
i + 0x, i + 1x, i + 2x, ...
Where x is your number of items divided by the number of columns.
and you stop iterating when i = total / x
Sorry to be too tired to code this for you but the gist is this:
$myarray = [1 ... 15];
$columns = 3;
$arrayKeys = array_keys($myarray);
$total = count($array);
$x = floor $total / $column;
for ($i = 0; $i > $x; $i += $x + 1 ){
echo $arrayKeys[$i] . " - " . $myarray($arrayKeys[$i]);
echo $arrayKeys[$i + $x] . " - " . $myarray($arrayKeys[$i + $x]);
echo $arrayKeys[$i + ($x * 2) ] . " - " . $myarray($arrayKeys[$i + ($x * 2)]);
}
Or something like that... that's off the top of my head and I think it has some issues, but you should be able to beat that into something that works.
<?php
$xml = simplexml_load_string( $response->ApiCallDeatilDataFeedResult );
foreach ( $xml->call_data as $data )
{
?>
<tr>
<td class="sss"><?php
echo $data->call_time;?></td>
<td class="sss"><?php
$init = $data->call_duration;
$hours = floor($init / 3600);
$minutes = floor(($init / 60) % 60);
$seconds = $init % 60;
echo "$minutes Min : $seconds Sec";
?></td>
<td class="sss"><?php echo $data->call_status;?></td>
<td class="sss"><?php echo $data->caller_number;?></td>
<td class="sss"><?php echo $data->caller_name;?></td>
<td class="sss"><?php echo $data->caller_city;?></td>
<td class="sss"><?php echo $data->caller_state;?></td>
<td class="sss"><?php echo $data->caller_zip;?></td>
</tr>
<?php
}
?>
</table>
While request the xml i reciveing xml response which is give result in ascending order. I need XML response in descending order and need no of rows in total.
Use krsort for the sorting. And yeah use count() to count the array.
Simplexml is offering an iterator for the foreach, if you want to reverse it, you could convert it to an array, reverse the array and then foreach over the array:
$datas = $xml->call_data;
$datas = iterator_to_array($datas, 0);
$datas = array_reverse($datas);
foreach($datas as $data)
{
...
}
$count = count($datas);
The answer of #Yogesh Suthar is correct (despite calling count on $xml directly instead of $xml->call_data) , but I think the indices are wrong since an array index starts from zero and ends at length-1.
EDIT:
As #hakra stated in the comments, call_data is not an array, but an iterable SimpleXMLElement.
But for the sake of argument, let us say that it is. So, I think it should be:
for($i = count($xml->call_data) - 1 ;$i >= 0 ; $i--)
Or, if you want to avoid the trouble of using indices, try using array_reverse if call_data is indeed an array
foreach ( array_reverse($xml->call_data) as $data )
use count for number of rows and use for loop in reverse for descending order like this example
for($i = count($xml) ;$i >0 ; $i--)
{
// your code
}