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;
Related
I have a set of numbers from MySQL within the range 1000 0000 (8 digits) to 9 999 999 999 (10 digits). It's supposed to be consecutive, but there are missing numbers. I need to know which numbers are missing.
The range is huge. At first I was going to use PHP to do this:
//MySqli Select Query
$results = $mysqli->query("SELECT `OCLC Number` FROM `MARC Records by Number`");
$n_array = array();
while($row = $results->fetch_assoc()) {
$n_array[] = $row["OCLC Number"];
}
d($n_array);
foreach($n_array as $k => $val) {
print $val . " ";
}
/* 8 digits */
$counter = 10000000;
$master_array = array();
/* 10 digits */
while ($counter <= 9999999999 ) {
$master_array[] = $counter;
$counter++;
d($master_array);
}
d($master_array);
$missing_numbers_ar = array_diff ($master_array, $n_array);
d($missing_numbers_ar);
d() is a custom function akin to var_dump().
However, I just realized it would take tons of time for this to be done. At the 15 minute mark, $master_array is being populated with only 4000 numbers.
How can I do this in a quicker way? MySQL-only or MySQL-and-PHP solutions both welcome. If the optimal solution depends on how many numbers are missing, please let me know how so. Tq.
Your d() probably is the cause of slowness, please remove it, and make small changes in your code
while($row = $results->fetch_assoc()) {
$n_array[$row["OCLC Number"]] = 1;
}
and
$missing_numbers_ar = [];
while ($counter++ <= 9999999999 ) {
if (empty($n_array[$counter])) {
$missing_numbers_ar[] = $counter;
}
}
If the following is still slow I would be surprised. I also just noticed it is similar to #Hieu Vo's answer.
// Make sure the data is returned in order by adding
// an `ORDER BY ...` clause.
$results = $mysqli->query("SELECT `OCLC Number`
FROM `MARC Records by Number`
ORDER BY `OCLC Number`");
$n_array = array();
while($row = $results->fetch_assoc()) {
// Add the "OCLC Number" as a key to the array.
$n_array[$row["OCLC Number"]] = $row["OCLC Number"];
}
// assume the first array key is in fact correct
$i = key($n_array);
// get the last key, also assume it is not missing.
end($n_array);
$max = key($n_array);
// reset the array (should not be needed)
reset($n_array);
do {
if (! $n_array[$i]) {
echo 'Missing key:['.$i.']<br />';
// flush the data to the page as you go.
flush();
}
} while(++$i <= $max);
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;
Okay so, I made an array containing 270+ different strings. The main goal is too echo out 60 strings from that array and combine them..
Ex. 1.String, 1.String2.
The 2 echo'd out strings are a combination, and should be together like 1-1 and 2-2, 3-3, and ect. In total there would be 30 combinations, but 60 strings.
Also, the way I have it is the first generated string should be combo'd with the 31st string generated
I was able to do this using a for loop, but now I had to use a mysql database to check if that combination already exists, then tell the random operator to generate another combination, until it finds a combination that doesn't already exist in the table. Here is what I have so far, but I'm not sure where to go from here.
$input = array("ITEM1", "ITEM2", "ITEM3", "ITEM4", "ITEM5"); //There are 273 items in the list
$rand_keys = array_rand($input, 60);
$con = mysqli_connect($server, $user, $password, $name_db);
for ($i = 0; $i <= 29; $i++) {
$check = "SELECT * FROM contest WHERE name1 = '$input[$rand_keys[$i]]' AND name2 = '$input[$rand_keys[$i+30]]'";
$rs = mysqli_query($con, $check);
$data = mysqli_fetch_array($rs, MYSQLI_NUM);
if ($data[$i] > 1) {
//This combination already exists generate a new one until it generates one that doesn't exist
while ($data[$i] > 1) {
$rand_keys2 = array_rand($input, 2);
$input[$rand_keys2[0]] = $input[$rand_keys[$i]];
$input[$rand_keys2[1]] = $input[$rand_keys[$i + 30]];
}
echo $input[$rand_keys[$i]];
echo '-';
echo $input[$rand_keys[$i + 30]];
} else {
echo $input[$rand_keys[$i]];
echo '-';
echo $input[$rand_keys[$i + 30]];
}
}
That is all I have so far, I'm pretty sure my error is in the mysql statement could anyone fix that for me, and there is probably a bunch of mistakes in the rest of it. I'm just beginning, so don't mind some noob mistakes if you see them. Btw, when I run it, it just comes to a blank page.
In my personal opinion, NEVER try to get data from an array within quotes! Always do it outside of quotes; especially in multi-denominational arrays.
'$input[$rand_keys[$i]]' should be rewritten as '".$input[$rand_keys[$i]]."' OR '{$input[$rand_keys[$i]]}'.
In my opinion it is better to do it outside of quotes instead of using { }.
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
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) . '%';
}