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 total all the results inside that while loop? (Total of 133) Thanks.
EDIT:
How about if I want to 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..
Try something like this:
$Sum = 0;
while ($SomeInvariant)
{
mysql_query($SomeQuery);
$Sum += mysql_num_rows();
}
echo 'The sum is: ' . $Sum;
However, this approach is not very efficient (what if $SomeInvariant is true for many iterations, and your app has even more concurrent users?). To account for this, I would recommend restructuring your approach so the addition is done in SQL. This way, your query could look something like this: SELECT SUM(ColumnName) FROM ....
UPDATE: Addressing follow-up question in the comments
If you don't already have the sum available from the query, then you'll have to loop over the dataset twice. On the first pass, you'll calculate the sum. On the second pass, you'll calculate the ratio of each value to the sum.
For example:
$Sum = 0;
$Rows = array();
while ($SomeInvariant)
{
mysql_query($SomeQuery);
$Value = mysql_num_rows();
$Rows[] = $Value; // Push the value onto the row array
$Sum += $Value; // Add the value to the cumulative sum
}
echo 'The sum is: ' . $Sum;
foreach ($Rows as $Row)
{
echo $Row . '/' . $Sum . ' = ' . number_format($Row / $Sum) . '%';
}
Related
I am looking way to sort the serial number of the table in descending order. I am using a here simple while loop, with a counter variable inside it.
Code sample:
$i= 0;
while(condition)
{
$i++;
echo "<td>".$i."</td>";
}
Output:
I am not using an autoincrement column here. I just want it with a simple counter, but in descending order.
example:
#
10
9
8
7
6
5
4
3
2
1
Any help is highly appreciated.
If you already have loop outputting the 1-10 version, you could simple change the output to show 11 minus the current count...
echo "<td>".(11-$i)."</td>";
Or to change the whole code, you could start at 11 and decrement the counter each time and output it that way
$i= 11;
while($i>0)
{
$i--;
echo "<td>".$i."</td>";
}
count first and after do a loop in reverse order
$i= 0;
while(condition)
{
$i++;
}
for ( cnt= $i, $i>= 0, $i--){
echo "<td>".$cnt."</td>";
}
If you are fetching from MYSQL Database and you're using PDO to connect to Database
//COUNT THE TOTAL NUMBER OF ROWS RETURNED
$sql = "SELECT COUNT(*) FROM all_tnxs ORDER BY id DESC";
$stmt = $con->query($sql);
$stmt_num_rows = $stmt->fetch();
$tot_rows = array_shift($stmt_num_rows);
$sn = $tot_rows
while(){
$sn--;
echo '<td>' . $sn . '</td>';
}
So whatever the total number of rows you have - fetching from the database it'll countdown to '0'using the while loop.
I have been looking for this for long but later figured it out myself so I decided to drop it here for anyone it might be helpful to...
I echo some numbers from the database and show only those numbers with a foreach. I now want to calculate the total of these numbers.
$test = str_replace('\\', '', $orderDetails['jsonData']);
$bonbonOrders = unserialize($test);
foreach($bonbonOrders as $bonbonOrder){
foreach($bonbonOrder as $bonbons){
echo $bonbons['gewicht'];
}
}
I tried several things but I really don't know how I can calculate them.
the output for a example can be:
18 15 16 12 11
Thanks!
This depends how you are getting those numbers from your database. However, since you are deserializing something I will assume that it cannot be done in a simple SQL query.
The following code should echo out the total of all of the numbers.
$test = str_replace('\\', '', $orderDetails['jsonData']);
$bonbonOrders = unserialize($test);
$nums = array();
foreach($bonbonOrders as $bonbonOrder){
foreach($bonbonOrder as $bonbons){
$nums[] =$bonbons['gewicht'];
}
}
$total = array_sum($nums);
echo $total;
Achieved by adding all of the numbers to an array, and calling array_sum on the final array.
Another alternative would have been to create $total = 0 before the foreach and to simply increment it as you get access to each number.
Simply addup each $bonbons['gewicht'] value in a variable and echo it
$test = str_replace('\\', '', $orderDetails['jsonData']);
$bonbonOrders = unserialize($test);
$sum =0;
foreach($bonbonOrders as $bonbonOrder){
foreach($bonbonOrder as $bonbons){
echo $bonbons['gewicht'];
$sum += $bonbons['gewicht'];
}
}
echo $sum;
I have an array of value series like:
$series = [100,300,500,800,1000,3000,5000,10000,15000,20000];
Another value getting from DB like:
$point = $data[‘earned_point’];
I need the highest match from the series. such as I got a value from db (1500) the highest match of the value is 1000 in the series, so I need to get the $series[4] and make it
$reward = $series[4] * 0.1;
I'll run it in a loop to do it for all the values got from DB.
I'm posting alternate code as the accepted answer while is correct can be very inefficient if you are working with a large array.
<?php
function computeReward($series, $point, $percent = 0.1){
arsort($series); // sort the series in reverse so we can pass any array and the highest number will be the first because we are looking for a number lower or equal to our point
foreach($series as $min_point){
if($min_point <= $point){
return $min_point * $percent; // return the min_point * the percentage, this stops the loop there for being more efficient
}
}
}
$series = [100,300,500,800,1000,3000,5000,10000,15000,20000];
$point = $data['earned_point'];
$reward = computeReward($series, $point);
?>
Do you mean you want to get which highest $series item is equal or less than $point ?
<?php
$series = [100,300,500,800,1000,3000,5000,10000,15000,20000];
$point = $data['earned_point'];
foreach ($series as $min_point) {
if ($point >= $min_point) {
$matched_min_point = $min_point;
}
}
$reward = $matched_min_point*0.1;
Let me know if this works for you
in mock test, i store id of questions in an array and i want when test start then it generate radomly id's from this array. when id is less then 10 then it generate correct number but when it store greater then 10 like 20,21,22.. then it also generate also number form 1-10. i want it generate random number from number which store in this array. thnax..
$ids= array('20','21','22','23','24','25','26','27','28','29','30','31','32',);
$getIds=mysql_query("select * from mock_test_question where status='1' and question_level='FINAL' ") or die(mysql_error());
while($data=mysql_fetch_array($getIds))
{
array_push($ids, $data['id']);
}
print_r($ids);
echo "</br>";
$rand_keys = array_rand($ids,5);
$_SESSION['quesid']=$rand_keys;
print_r($rand_keys);
array_rand returns the KEYS (array positions) not the actual values. To get the values:
echo $ids[$rand_keys];
This should give you a random number
$randomValues = array('20','21','22','23','24','25','26','27','28','29','30','31','32');
$randomValuesIndex = array_rand($randomValues, 1);
$randomValue = $randomValues[$randomValuesIndex];
echo $randomValue."\n";
An example loop that generates random numbers
$randomValues = array('20','21','22','23','24','25','26','27','28','29','30','31','32');
for ($i = 1; $i < 30; $i++)
{
$randomValuesIndex = array_rand($randomValues, 1);
$randomValue = $randomValues[$randomValuesIndex];
echo $randomValue."\n";
}
$count = count($ids) - 1; # note that its -1 because array keys start from 0
echo $ids[rand(0,$count)];
here is a fast way to get random element from array
P.S>
Here is complete code with generate of numbers and usage..
$ids = array();
for($i=20;$i<=32;$i++){ $ids[]=$i; }
$count = count($ids) - 1;
echo $ids[rand(0,$count)];
echo $ids[rand(0,$count)];
echo $ids[rand(0,$count)];
I have created an array of data, from which I can loop through specific fields and echo these values out, but what I need to do is add these values to a new array, ultimately allowing me to find the average of the values in the new array. As i've said, I can echo out the data, and I think I've figured how to get the average, if only I can create the new array! Any help would be greatly appreciated as I just can't find the answer anywhere, and I'm running low on talent!
My table contains approx 25 fields, im pulling out a number of rows based on a session variable. In the instance im working on, I need to take just the values from 1 column in the table, and add these to an array. The code below will loop through the values, and echo them out, 1 at a time:-
while ($cdarray=mysql_fetch_array($calldata)) {
echo $cdarray['score_total'];
}
This gives me 25555 which are the 4 values I would expect 25, 5, 5, 5
I've tried
while ($cdarray=mysql_fetch_array($calldata)) {
$cdts = $cdarray['score_total'];
$cdtsar = array($cdts);
}
Which results in $cdts being assigned a value of 5,
Any help greatly appreciated!!
This will get your data from the array, place it into a new one and calculates the average.
$cdtsar = array();
while ($cdarray=mysql_fetch_array($calldata)) {
$cdtsar[] = $cdarray['score_total'];
}
$average = array_sum($cdtsar) / count($cdtsar);
It actually prints 25 and 5 and 5 and 5, but there are no spaces in between so it looks like "25555". To verify this yourself:
while ($cdarray=mysql_fetch_array($calldata)) {
echo $cdarray['score_total'];
echo " / ";
}
To get the average, you can either use
$sum = $count = 0;
$average = null;
while ($cdarray=mysql_fetch_array($calldata)) {
$sum += $cdarray['score_total'];
++$count;
}
// Make sure to guard against divide by zero
if ($count) {
$average = $sum / $count;
}
or you might have the database calculate the average for you, if changing the query is an option.
If you want to assign the elements to the new array use like this
$cdtsar = array();
while ($cdarray=mysql_fetch_array($calldata)) {
array_push($cdtsar,$cdarray['score_total']);
}
To find the average of the array
$sum = array_sum($cdtsar);
$num = sizeof($cdtsar);
$avg = $sum/$num;
echo $avg;